<?php

namespace App\Helpers\Equipment;

use App\Entities\CommonEntity;
use App\Models\Equipment\ServerPartModel;

class ServerPartHelper extends EquipmentHelper
{
    public function __construct()
    {
        parent::__construct();
        $this->setTitleField(field: ServerPartModel::TITLE);
    }
    protected function form_dropdown_common_process(string $field, mixed $value, array $viewDatas, array $extras = [], array $attributes = [], bool $isAll = false): string
    {
        $html = "";
        switch ($field) {
            case 'part_uid':
                if (!array_key_exists('type', $viewDatas['control']['form_datas']) || !$viewDatas['control']['form_datas']['type']) {
                    throw new \Exception(__METHOD__ . "에서 오류발생: Type가 정의되지 않았습니다.");
                }
                foreach ($viewDatas['control']['field_optons'][$field][$viewDatas['control']['form_datas']['type']] as $option_key => $option_value) {
                    $isSelected = $option_key == $value ? ' selected' : '';
                    $isDisabled = "";
                    $attribute  = "";
                    $label      = "";
                    if ($option_value instanceof CommonEntity) {
                        if ($option_key != $value && $option_value->getStatus() != $option_value::DEFAULT_STATUS && !$isAll) {
                            continue;
                        }
                        foreach ($attributes as $attribute_name => $attribute_value) {
                            $attribute .= sprintf(" %s=\"%s\"", $attribute_name, $option_value->$attribute_value);
                        }
                        $label = $option_value->getCustomTitle();
                    } else {
                        $label = $option_value;
                    }
                    $html .= sprintf("<option value=\"%s\"%s%s%s>%s</option>", $option_key, $isSelected, $isDisabled, $attribute, $label);
                }
                break;
            default:
                $html = parent::form_dropdown_common_process($field, $value, $viewDatas, $extras, $attributes);
                break;
        }
        return $html;
    }
    public function getFieldForm(string $field, mixed $value, array $viewDatas, array $extras = []): string
    {
        switch ($field) {
            case 'part_uid':
                $extras['class'] = array_key_exists('class', $extras) ? $extras['class'] . ' select-field' : 'select-field';
                $extras['onChange'] = "document.querySelector('input[name=\'title\']').value = this.options[this.selectedIndex].getAttribute('data-title'); document.querySelector('input[name=\'amount\']').value = this.options[this.selectedIndex].getAttribute('data-price')";
                $attributes = ['data-title' => 'title', 'data-price' => 'price'];
                $form = $this->form_dropdown_common($field, $value, $viewDatas, $extras, $attributes);
                break;
            case 'extra':
                if (array_key_exists('type', $viewDatas['control']['form_datas']) && $viewDatas['control']['form_datas']['type'] === 'DISK') {
                    $options = ["" => lang("{$viewDatas['class_path']}.label.{$field}") . " 선택", ...lang("{$viewDatas['class_path']}.EXTRA.{$viewDatas['control']['form_datas']['type']}")];
                    $form = form_dropdown($field, $options, $value, $extras);
                } else {
                    $form = parent::getFieldForm($field, $value, $viewDatas, $extras);;
                }
                break;
            default:
                $form = parent::getFieldForm($field, $value, $viewDatas, $extras);
                break;
        }
        return $form;
    }
    public function getFieldView(string $field, mixed $value, array $viewDatas, array $extras = []): string|null
    {
        switch ($field) {
            case 'SERVER':
                $value = form_label(
                    sprintf(
                        "[%s] %s",
                        lang("Equipment/Server.TYPE")[$viewDatas['serverEntity']->getType()],
                        $viewDatas['serverEntity']->getCode(),
                    ),
                    $field,
                    [
                        "data-src"       => "/admin/equipment/server/modify/{$viewDatas['serverEntity']->getPK()}?ActionTemplate=server",
                        "data-bs-toggle" => "modal",
                        "data-bs-target" => "#modal_action_form",
                        "class"          => "btn btn-sm form-label-sm text-primary",
                        ...$extras,
                    ]
                );
                break;
            case 'CPU':
            case 'RAM':
            case 'DISK':
            case 'SOFTWARE':
            case 'IP':
            case 'CS':
                //파트 Entity
                $title =  $viewDatas['entity']->getTitle();
                $title .= $viewDatas['entity']->getCnt() > 1 ? "*" . $viewDatas['entity']->getCnt() . "개" : "";
                $title .= $viewDatas['entity']->getExtra() ? "[" . $viewDatas['entity']->getExtra() . "]" : "";
                if (array_key_exists('return',  $extras) && $extras['return'] == 'onlyText') {
                    $value = $title;
                } else {
                    $billing = $viewDatas['entity']->getBilling() === "" ? "" : ($viewDatas['entity']->getBilling() === PAYMENT['BILLING']["ONETIME"] ? ICONS['ONETIME'] : ($viewDatas['entity']->getBilling() === PAYMENT['BILLING']["MONTH"] ? ICONS['MONTH'] : ""));
                    $value = form_label(
                        $billing . $title,
                        $field,
                        [
                            "data-src"       => "/admin/equipment/serverpart/modify/{$viewDatas['entity']->getPK()}?type={$viewDatas['entity']->getType()}&ActionTemplate=popup",
                            "data-bs-toggle" => "modal",
                            "data-bs-target" => "#modal_action_form",
                            "class"          => "btn btn-sm form-label-sm text-primary",
                            ...$extras,
                        ]
                    );
                }
                break;
            default:
                $value = parent::getFieldView($field, $value, $viewDatas, $extras);
                break;
        }
        if (is_array($value)) {
            throw new \Exception(__METHOD__ . "에서 오류: {$field}의 값이 Array형태입니다");
        }
        return $value;
    }
    public function getListButton(string $action, string $label, array $viewDatas, array $extras = []): string
    {
        switch ($action) {
            case 'IP':
            case 'CS':
            case 'CPU':
            case 'RAM':
            case 'DISK':
            case 'SOFTWARE':
                $action = form_label(
                    $label ? $label : ICONS["SERVER_ITEM_{$action}"],
                    $action,
                    [
                        "data-src"       => "/admin/equipment/serverpart/create?serverinfo_uid={$viewDatas['serverinfo_uid']}&type={$action}&ActionTemplate=popup",
                        "data-bs-toggle" => "modal",
                        "data-bs-target" => "#modal_action_form",
                        "class"          => "btn btn-sm form-label-sm text-primary",
                        ...$extras,
                    ]
                );
                break;
            default:
                $action = parent::getListButton($action, $label, $viewDatas, $extras);
                break;
        }
        return $action;
    }
}
