<template>
  <div>
    <gz-report-selector ref="reportSelector"></gz-report-selector>
    <div v-if="formState.ready">
      <gz-error :error-box-message="formState.errorBoxMessage"></gz-error>
      <v-form ref="form">
        <v-row dense>
          <!-- <v-col cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              ref="name"
              v-model="obj.name"
              dense
              :readonly="formState.readOnly"
              :label="$sock.t('SubServerName')"
              :rules="[form().required(this, 'name')]"
              :error-messages="form().serverErrors(this, 'name')"
              data-cy="name"
              @input="fieldValueChanged('name')"
            ></v-text-field>
          </v-col> -->
          <v-col cols="12" sm="6" lg="4" xl="3">
            <gz-ssh
              ref="name"
              v-model="obj.name"
              :readonly="formState.readOnly"
              :label="$sock.t('SubServerName')"
              data-cy="name"
              :rules="[form().required(this, 'name')]"
              :error-messages="form().serverErrors(this, 'name')"
              @input="fieldValueChanged('name')"
            ></gz-ssh>
          </v-col>
          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              ref="ipAddress"
              v-model="obj.ipAddress"
              dense
              :readonly="formState.readOnly"
              :label="$sock.t('SubServerIP')"
              data-cy="ipAddress"
              :error-messages="form().serverErrors(this, 'ipAddress')"
              @input="fieldValueChanged('ipAddress')"
            ></v-text-field>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <gz-pick-list
              ref="customerId"
              v-model="obj.customerId"
              :aya-type="sockTypes().Customer"
              show-edit-icon
              :readonly="formState.readOnly"
              :label="$sock.t('Customer')"
              :error-messages="form().serverErrors(this, 'customerId')"
              @input="fieldValueChanged('customerId')"
            ></gz-pick-list>
          </v-col>
          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-select
              ref="serverState"
              v-model="obj.serverState"
              dense
              :items="selectLists.serverStates"
              item-text="name"
              item-value="id"
              :readonly="formState.readOnly"
              :label="$sock.t('ServerState')"
              data-cy="serverState"
              :rules="[form().integerValid(this, 'serverState')]"
              :error-messages="form().serverErrors(this, 'serverState')"
              @input="fieldValueChanged('serverState')"
            ></v-select>
          </v-col>
          <v-col cols="12" sm="6" lg="4" xl="3">
            <gz-date-time-picker
              ref="created"
              v-model="obj.created"
              :label="$sock.t('Created')"
              :rules="[form().required(this, 'created')]"
              :readonly="formState.readOnly"
              :error-messages="form().serverErrors(this, 'created')"
              data-cy="created"
              @input="fieldValueChanged('created')"
            ></gz-date-time-picker>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-select
              ref="dataCenter"
              v-model="obj.dataCenter"
              dense
              :items="selectLists.dataCenters"
              item-text="name"
              item-value="id"
              :label="$sock.t('SubServerDatacenter')"
              :error-messages="form().serverErrors(this, 'dataCenter')"
              :rules="[form().required(this, 'dataCenter')]"
              @input="fieldValueChanged('dataCenter')"
            ></v-select>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-select
              ref="timeZone"
              v-model="obj.timeZone"
              dense
              :items="selectLists.timeZones"
              :label="$sock.t('SubServerTimeZone')"
              :error-messages="form().serverErrors(this, 'timeZone')"
              :rules="[form().required(this, 'timeZone')]"
              @input="fieldValueChanged('timeZone')"
            ></v-select>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              ref="dbId"
              v-model="obj.dbId"
              dense
              :readonly="formState.readOnly"
              :label="$sock.t('DatabaseID')"
              data-cy="dbId"
              :error-messages="form().serverErrors(this, 'dbId')"
              @input="fieldValueChanged('dbId')"
            ></v-text-field>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <gz-date-time-picker
              ref="lastUpdated"
              v-model="obj.lastUpdated"
              :label="$sock.t('SubServerLastUpdated')"
              :readonly="formState.readOnly"
              :error-messages="form().serverErrors(this, 'lastUpdated')"
              data-cy="lastUpdated"
              @input="fieldValueChanged('lastUpdated')"
            ></gz-date-time-picker>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-row no-gutters>
              <v-col cols="1">
                <v-menu offset-y>
                  <template v-slot:activator="{ on, attrs }">
                    <v-btn icon v-bind="attrs" v-on="on">
                      <v-icon small>$sockiPlus</v-icon>
                    </v-btn>
                  </template>
                  <v-list>
                    <v-list-item @click="subExpireAddOneWeek">
                      <v-list-item-icon>
                        <v-icon>$sockiPlus</v-icon>
                      </v-list-item-icon>
                      <v-list-item-title>One week</v-list-item-title>
                    </v-list-item>
                    <v-list-item @click="subExpireAddOneMonth">
                      <v-list-item-icon>
                        <v-icon>$sockiPlus</v-icon>
                      </v-list-item-icon>
                      <v-list-item-title>One month</v-list-item-title>
                    </v-list-item>
                    <v-list-item @click="subExpireAddOneYear">
                      <v-list-item-icon>
                        <v-icon>$sockiPlus</v-icon>
                      </v-list-item-icon>
                      <v-list-item-title>One year</v-list-item-title>
                    </v-list-item>
                  </v-list>
                </v-menu>
              </v-col>
              <v-col>
                <gz-date-time-picker
                  ref="subscriptionExpire"
                  v-model="obj.subscriptionExpire"
                  :label="$sock.t('SubServerSubExpire')"
                  :rules="[form().required(this, 'subscriptionExpire')]"
                  :readonly="formState.readOnly"
                  :error-messages="
                    form().serverErrors(this, 'subscriptionExpire')
                  "
                  data-cy="subscriptionExpire"
                  @input="fieldValueChanged('subscriptionExpire')"
                ></gz-date-time-picker>
              </v-col>
            </v-row>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              ref="lastHealthStatus"
              v-model="obj.lastHealthStatus"
              dense
              readonly
              :label="$sock.t('SubServerLastHealthStatus')"
              data-cy="lastHealthStatus"
            ></v-text-field>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <gz-date-time-picker
              ref="lastHealthCheck"
              v-model="obj.lastHealthCheck"
              :label="$sock.t('SubServerLastHealthCheck')"
              readonly
              data-cy="lastHealthCheck"
            ></gz-date-time-picker>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              ref="operatingSystem"
              v-model="obj.operatingSystem"
              dense
              :readonly="formState.readOnly"
              :label="$sock.t('SubServerOperatingSystem')"
              data-cy="operatingSystem"
              :error-messages="form().serverErrors(this, 'operatingSystem')"
              @input="fieldValueChanged('operatingSystem')"
            ></v-text-field>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              ref="customerSubDomain"
              v-model="obj.customerSubDomain"
              dense
              :readonly="formState.readOnly"
              :label="$sock.t('SubServerCustomerDomain')"
              data-cy="customerSubDomain"
              :error-messages="form().serverErrors(this, 'customerSubDomain')"
              @input="fieldValueChanged('customerSubDomain')"
            ></v-text-field>
          </v-col>
          <v-col cols="12" sm="6" lg="4" xl="3">
            <gz-currency
              ref="cost"
              v-model="obj.cost"
              :readonly="formState.readOnly"
              :label="$sock.t('LoanUnitRateMonthCost')"
              data-cy="cost"
              :rules="[
                form().decimalValid(this, 'cost'),
                form().required(this, 'cost')
              ]"
              :error-messages="form().serverErrors(this, 'cost')"
              @input="fieldValueChanged('cost')"
            ></gz-currency>
          </v-col>
          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-checkbox
              ref="trial"
              v-model="obj.trial"
              dense
              :readonly="formState.readOnly"
              :label="$sock.t('SubServerTrial')"
              data-cy="trial"
              :error-messages="form().serverErrors(this, 'trial')"
              @change="fieldValueChanged('trial')"
            ></v-checkbox>
          </v-col>

          <v-col v-if="obj.trial" cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              ref="trialCompany"
              v-model="obj.trialCompany"
              dense
              :readonly="formState.readOnly"
              :label="$sock.t('SubServerTrialCompany')"
              data-cy="trialCompany"
              :error-messages="form().serverErrors(this, 'trialCompany')"
              @input="fieldValueChanged('trialCompany')"
            ></v-text-field>
          </v-col>

          <v-col v-if="obj.trial" cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              ref="trialContact"
              v-model="obj.trialContact"
              dense
              :readonly="formState.readOnly"
              :label="$sock.t('SubServerTrialContact')"
              data-cy="trialContact"
              :error-messages="form().serverErrors(this, 'trialContact')"
              @input="fieldValueChanged('trialContact')"
            ></v-text-field>
          </v-col>

          <v-col v-if="obj.trial" cols="12" sm="6" lg="4" xl="3">
            <gz-email
              ref="trialEmail"
              v-model="obj.trialEmail"
              :readonly="formState.readOnly"
              :label="$sock.t('SubServerTrialEmail')"
              data-cy="trialEmail"
              :error-messages="form().serverErrors(this, 'trialEmail')"
              @input="fieldValueChanged('trialEmail')"
            ></gz-email>
          </v-col>

          <v-col v-if="form().showMe(this, 'SubServerNotes')" cols="12">
            <v-textarea
              ref="notes"
              v-model="obj.notes"
              dense
              :readonly="formState.readOnly"
              :label="$sock.t('SubServerNotes')"
              :error-messages="form().serverErrors(this, 'notes')"
              data-cy="notes"
              auto-grow
              @input="fieldValueChanged('notes')"
            ></v-textarea>
          </v-col>
          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-checkbox
              ref="active"
              v-model="obj.active"
              dense
              :readonly="formState.readOnly"
              :label="$sock.t('Active')"
              data-cy="active"
              :error-messages="form().serverErrors(this, 'active')"
              @change="fieldValueChanged('active')"
            ></v-checkbox>
          </v-col>
          <!-- --------------------------------- -->

          <v-col v-if="form().showMe(this, 'Tags')" cols="12">
            <gz-tag-picker
              ref="tags"
              v-model="obj.tags"
              :readonly="formState.readOnly"
              data-cy="tags"
              :error-messages="form().serverErrors(this, 'tags')"
              @input="fieldValueChanged('tags')"
            ></gz-tag-picker>
          </v-col>

          <v-col v-if="form().showMe(this, 'Wiki')" cols="12">
            <gz-wiki
              ref="wiki"
              v-model="obj.wiki"
              :aya-type="sockType"
              :aya-id="obj.id"
              :readonly="formState.readOnly"
              @input="fieldValueChanged('wiki')"
            ></gz-wiki
          ></v-col>

          <v-col v-if="form().showMe(this, 'Attachments') && obj.id" cols="12">
            <gz-attachments
              :readonly="formState.readOnly"
              :aya-type="sockType"
              :aya-id="obj.id"
            ></gz-attachments
          ></v-col>
        </v-row>
      </v-form>
    </div>
    <v-overlay :value="!formState.ready || formState.loading">
      <v-progress-circular indeterminate :size="64" />
    </v-overlay>
  </div>
</template>
<script>
const FORM_KEY = "subscription-server-edit";
const API_BASE_URL = "subscription-server/";
const FORM_CUSTOM_TEMPLATE_KEY = "SubscriptionServer";
export default {
  data() {
    return {
      formCustomTemplateKey: FORM_CUSTOM_TEMPLATE_KEY,
      obj: {
        id: 0,
        concurrency: 0,
        name: null,
        active: true,
        customerId: null,
        serverState: 0,
        notes: null,
        created: window.$gz.locale.nowUTC8601String(),
        dataCenter: null,
        timeZone: null,
        dbId: null,
        lastUpdated: null,
        subscriptionExpire: null,
        lastHealthStatus: null,
        lastHealthCheck: null,
        trial: true,
        trialContact: null,
        trialEmail: null,
        trialCompany: null,
        operatingSystem: "Ubuntu 22.10",
        customerSubDomain: null,
        cost: 7.0,
        wiki: null,
        tags: []
      },
      selectLists: {
        serverStates: [],
        dataCenters: [
          { id: "SF", name: "San Francisco" },
          { id: "NY", name: "New York" },
          { id: "TOR", name: "Toronto" },
          { id: "AMS", name: "Amsterdam" },
          { id: "LON", name: "London" },
          { id: "FFT", name: "Frankfurt" },
          { id: "SNG", name: "Singapore" },
          { id: "BNG", name: "Bangalore" },
          { id: "SYD", name: "Sydney Australia" }
        ],
        timeZones: [
          "Africa/Abidjan",
          "Africa/Accra",
          "Africa/Addis_Ababa",
          "Africa/Algiers",
          "Africa/Asmara",
          "Africa/Asmera",
          "Africa/Bamako",
          "Africa/Bangui",
          "Africa/Banjul",
          "Africa/Bissau",
          "Africa/Blantyre",
          "Africa/Brazzaville",
          "Africa/Bujumbura",
          "Africa/Cairo",
          "Africa/Casablanca",
          "Africa/Ceuta",
          "Africa/Conakry",
          "Africa/Dakar",
          "Africa/Dar_es_Salaam",
          "Africa/Djibouti",
          "Africa/Douala",
          "Africa/El_Aaiun",
          "Africa/Freetown",
          "Africa/Gaborone",
          "Africa/Harare",
          "Africa/Johannesburg",
          "Africa/Juba",
          "Africa/Kampala",
          "Africa/Khartoum",
          "Africa/Kigali",
          "Africa/Kinshasa",
          "Africa/Lagos",
          "Africa/Libreville",
          "Africa/Lome",
          "Africa/Luanda",
          "Africa/Lubumbashi",
          "Africa/Lusaka",
          "Africa/Malabo",
          "Africa/Maputo",
          "Africa/Maseru",
          "Africa/Mbabane",
          "Africa/Mogadishu",
          "Africa/Monrovia",
          "Africa/Nairobi",
          "Africa/Ndjamena",
          "Africa/Niamey",
          "Africa/Nouakchott",
          "Africa/Ouagadougou",
          "Africa/Porto-Novo",
          "Africa/Sao_Tome",
          "Africa/Timbuktu",
          "Africa/Tripoli",
          "Africa/Tunis",
          "Africa/Windhoek",
          "America/Adak",
          "America/Anchorage",
          "America/Anguilla",
          "America/Antigua",
          "America/Araguaina",
          "America/Argentina/Buenos_Aires",
          "America/Argentina/Catamarca",
          "America/Argentina/ComodRivadavia",
          "America/Argentina/Cordoba",
          "America/Argentina/Jujuy",
          "America/Argentina/La_Rioja",
          "America/Argentina/Mendoza",
          "America/Argentina/Rio_Gallegos",
          "America/Argentina/Salta",
          "America/Argentina/San_Juan",
          "America/Argentina/San_Luis",
          "America/Argentina/Tucuman",
          "America/Argentina/Ushuaia",
          "America/Aruba",
          "America/Asuncion",
          "America/Atikokan",
          "America/Atka",
          "America/Bahia",
          "America/Bahia_Banderas",
          "America/Barbados",
          "America/Belem",
          "America/Belize",
          "America/Blanc-Sablon",
          "America/Boa_Vista",
          "America/Bogota",
          "America/Boise",
          "America/Buenos_Aires",
          "America/Cambridge_Bay",
          "America/Campo_Grande",
          "America/Cancun",
          "America/Caracas",
          "America/Catamarca",
          "America/Cayenne",
          "America/Cayman",
          "America/Chicago",
          "America/Chihuahua",
          "America/Ciudad_Juarez",
          "America/Coral_Harbour",
          "America/Cordoba",
          "America/Costa_Rica",
          "America/Creston",
          "America/Cuiaba",
          "America/Curacao",
          "America/Danmarkshavn",
          "America/Dawson",
          "America/Dawson_Creek",
          "America/Denver",
          "America/Detroit",
          "America/Dominica",
          "America/Edmonton",
          "America/Eirunepe",
          "America/El_Salvador",
          "America/Ensenada",
          "America/Fort_Nelson",
          "America/Fort_Wayne",
          "America/Fortaleza",
          "America/Glace_Bay",
          "America/Godthab",
          "America/Goose_Bay",
          "America/Grand_Turk",
          "America/Grenada",
          "America/Guadeloupe",
          "America/Guatemala",
          "America/Guayaquil",
          "America/Guyana",
          "America/Halifax",
          "America/Havana",
          "America/Hermosillo",
          "America/Indiana/Indianapolis",
          "America/Indiana/Knox",
          "America/Indiana/Marengo",
          "America/Indiana/Petersburg",
          "America/Indiana/Tell_City",
          "America/Indiana/Vevay",
          "America/Indiana/Vincennes",
          "America/Indiana/Winamac",
          "America/Indianapolis",
          "America/Inuvik",
          "America/Iqaluit",
          "America/Jamaica",
          "America/Jujuy",
          "America/Juneau",
          "America/Kentucky/Louisville",
          "America/Kentucky/Monticello",
          "America/Knox_IN",
          "America/Kralendijk",
          "America/La_Paz",
          "America/Lima",
          "America/Los_Angeles",
          "America/Louisville",
          "America/Lower_Princes",
          "America/Maceio",
          "America/Managua",
          "America/Manaus",
          "America/Marigot",
          "America/Martinique",
          "America/Matamoros",
          "America/Mazatlan",
          "America/Mendoza",
          "America/Menominee",
          "America/Merida",
          "America/Metlakatla",
          "America/Mexico_City",
          "America/Miquelon",
          "America/Moncton",
          "America/Monterrey",
          "America/Montevideo",
          "America/Montreal",
          "America/Montserrat",
          "America/Nassau",
          "America/New_York",
          "America/Nipigon",
          "America/Nome",
          "America/Noronha",
          "America/North_Dakota/Beulah",
          "America/North_Dakota/Center",
          "America/North_Dakota/New_Salem",
          "America/Nuuk",
          "America/Ojinaga",
          "America/Panama",
          "America/Pangnirtung",
          "America/Paramaribo",
          "America/Phoenix",
          "America/Port-au-Prince",
          "America/Port_of_Spain",
          "America/Porto_Acre",
          "America/Porto_Velho",
          "America/Puerto_Rico",
          "America/Punta_Arenas",
          "America/Rainy_River",
          "America/Rankin_Inlet",
          "America/Recife",
          "America/Regina",
          "America/Resolute",
          "America/Rio_Branco",
          "America/Rosario",
          "America/Santa_Isabel",
          "America/Santarem",
          "America/Santiago",
          "America/Santo_Domingo",
          "America/Sao_Paulo",
          "America/Scoresbysund",
          "America/Shiprock",
          "America/Sitka",
          "America/St_Barthelemy",
          "America/St_Johns",
          "America/St_Kitts",
          "America/St_Lucia",
          "America/St_Thomas",
          "America/St_Vincent",
          "America/Swift_Current",
          "America/Tegucigalpa",
          "America/Thule",
          "America/Thunder_Bay",
          "America/Tijuana",
          "America/Toronto",
          "America/Tortola",
          "America/Vancouver",
          "America/Virgin",
          "America/Whitehorse",
          "America/Winnipeg",
          "America/Yakutat",
          "America/Yellowknife",
          "Antarctica/Casey",
          "Antarctica/Davis",
          "Antarctica/DumontDUrville",
          "Antarctica/Macquarie",
          "Antarctica/Mawson",
          "Antarctica/McMurdo",
          "Antarctica/Palmer",
          "Antarctica/Rothera",
          "Antarctica/South_Pole",
          "Antarctica/Syowa",
          "Antarctica/Troll",
          "Antarctica/Vostok",
          "Arctic/Longyearbyen",
          "Asia/Aden",
          "Asia/Almaty",
          "Asia/Amman",
          "Asia/Anadyr",
          "Asia/Aqtau",
          "Asia/Aqtobe",
          "Asia/Ashgabat",
          "Asia/Ashkhabad",
          "Asia/Atyrau",
          "Asia/Baghdad",
          "Asia/Bahrain",
          "Asia/Baku",
          "Asia/Bangkok",
          "Asia/Barnaul",
          "Asia/Beirut",
          "Asia/Bishkek",
          "Asia/Brunei",
          "Asia/Calcutta",
          "Asia/Chita",
          "Asia/Choibalsan",
          "Asia/Chongqing",
          "Asia/Chungking",
          "Asia/Colombo",
          "Asia/Dacca",
          "Asia/Damascus",
          "Asia/Dhaka",
          "Asia/Dili",
          "Asia/Dubai",
          "Asia/Dushanbe",
          "Asia/Famagusta",
          "Asia/Gaza",
          "Asia/Harbin",
          "Asia/Hebron",
          "Asia/Ho_Chi_Minh",
          "Asia/Hong_Kong",
          "Asia/Hovd",
          "Asia/Irkutsk",
          "Asia/Istanbul",
          "Asia/Jakarta",
          "Asia/Jayapura",
          "Asia/Jerusalem",
          "Asia/Kabul",
          "Asia/Kamchatka",
          "Asia/Karachi",
          "Asia/Kashgar",
          "Asia/Kathmandu",
          "Asia/Katmandu",
          "Asia/Khandyga",
          "Asia/Kolkata",
          "Asia/Krasnoyarsk",
          "Asia/Kuala_Lumpur",
          "Asia/Kuching",
          "Asia/Kuwait",
          "Asia/Macao",
          "Asia/Macau",
          "Asia/Magadan",
          "Asia/Makassar",
          "Asia/Manila",
          "Asia/Muscat",
          "Asia/Nicosia",
          "Asia/Novokuznetsk",
          "Asia/Novosibirsk",
          "Asia/Omsk",
          "Asia/Oral",
          "Asia/Phnom_Penh",
          "Asia/Pontianak",
          "Asia/Pyongyang",
          "Asia/Qatar",
          "Asia/Qostanay",
          "Asia/Qyzylorda",
          "Asia/Rangoon",
          "Asia/Riyadh",
          "Asia/Saigon",
          "Asia/Sakhalin",
          "Asia/Samarkand",
          "Asia/Seoul",
          "Asia/Shanghai",
          "Asia/Singapore",
          "Asia/Srednekolymsk",
          "Asia/Taipei",
          "Asia/Tashkent",
          "Asia/Tbilisi",
          "Asia/Tehran",
          "Asia/Tel_Aviv",
          "Asia/Thimbu",
          "Asia/Thimphu",
          "Asia/Tokyo",
          "Asia/Tomsk",
          "Asia/Ujung_Pandang",
          "Asia/Ulaanbaatar",
          "Asia/Ulan_Bator",
          "Asia/Urumqi",
          "Asia/Ust-Nera",
          "Asia/Vientiane",
          "Asia/Vladivostok",
          "Asia/Yakutsk",
          "Asia/Yangon",
          "Asia/Yekaterinburg",
          "Asia/Yerevan",
          "Atlantic/Azores",
          "Atlantic/Bermuda",
          "Atlantic/Canary",
          "Atlantic/Cape_Verde",
          "Atlantic/Faeroe",
          "Atlantic/Faroe",
          "Atlantic/Jan_Mayen",
          "Atlantic/Madeira",
          "Atlantic/Reykjavik",
          "Atlantic/South_Georgia",
          "Atlantic/St_Helena",
          "Atlantic/Stanley",
          "Australia/ACT",
          "Australia/Adelaide",
          "Australia/Brisbane",
          "Australia/Broken_Hill",
          "Australia/Canberra",
          "Australia/Currie",
          "Australia/Darwin",
          "Australia/Eucla",
          "Australia/Hobart",
          "Australia/LHI",
          "Australia/Lindeman",
          "Australia/Lord_Howe",
          "Australia/Melbourne",
          "Australia/NSW",
          "Australia/North",
          "Australia/Perth",
          "Australia/Queensland",
          "Australia/South",
          "Australia/Sydney",
          "Australia/Tasmania",
          "Australia/Victoria",
          "Australia/West",
          "Australia/Yancowinna",
          "Brazil/Acre",
          "Brazil/DeNoronha",
          "Brazil/East",
          "Brazil/West",
          "CET",
          "CST6CDT",
          "Canada/Atlantic",
          "Canada/Central",
          "Canada/Eastern",
          "Canada/Mountain",
          "Canada/Newfoundland",
          "Canada/Pacific",
          "Canada/Saskatchewan",
          "Canada/Yukon",
          "Chile/Continental",
          "Chile/EasterIsland",
          "Cuba",
          "EET",
          "EST",
          "EST5EDT",
          "Egypt",
          "Eire",
          "Etc/GMT",
          "Etc/GMT+0",
          "Etc/GMT+1",
          "Etc/GMT+10",
          "Etc/GMT+11",
          "Etc/GMT+12",
          "Etc/GMT+2",
          "Etc/GMT+3",
          "Etc/GMT+4",
          "Etc/GMT+5",
          "Etc/GMT+6",
          "Etc/GMT+7",
          "Etc/GMT+8",
          "Etc/GMT+9",
          "Etc/GMT-0",
          "Etc/GMT-1",
          "Etc/GMT-10",
          "Etc/GMT-11",
          "Etc/GMT-12",
          "Etc/GMT-13",
          "Etc/GMT-14",
          "Etc/GMT-2",
          "Etc/GMT-3",
          "Etc/GMT-4",
          "Etc/GMT-5",
          "Etc/GMT-6",
          "Etc/GMT-7",
          "Etc/GMT-8",
          "Etc/GMT-9",
          "Etc/GMT0",
          "Etc/Greenwich",
          "Etc/UCT",
          "Etc/UTC",
          "Etc/Universal",
          "Etc/Zulu",
          "Europe/Amsterdam",
          "Europe/Andorra",
          "Europe/Astrakhan",
          "Europe/Athens",
          "Europe/Belfast",
          "Europe/Belgrade",
          "Europe/Berlin",
          "Europe/Bratislava",
          "Europe/Brussels",
          "Europe/Bucharest",
          "Europe/Budapest",
          "Europe/Busingen",
          "Europe/Chisinau",
          "Europe/Copenhagen",
          "Europe/Dublin",
          "Europe/Gibraltar",
          "Europe/Guernsey",
          "Europe/Helsinki",
          "Europe/Isle_of_Man",
          "Europe/Istanbul",
          "Europe/Jersey",
          "Europe/Kaliningrad",
          "Europe/Kiev",
          "Europe/Kirov",
          "Europe/Kyiv",
          "Europe/Lisbon",
          "Europe/Ljubljana",
          "Europe/London",
          "Europe/Luxembourg",
          "Europe/Madrid",
          "Europe/Malta",
          "Europe/Mariehamn",
          "Europe/Minsk",
          "Europe/Monaco",
          "Europe/Moscow",
          "Europe/Nicosia",
          "Europe/Oslo",
          "Europe/Paris",
          "Europe/Podgorica",
          "Europe/Prague",
          "Europe/Riga",
          "Europe/Rome",
          "Europe/Samara",
          "Europe/San_Marino",
          "Europe/Sarajevo",
          "Europe/Saratov",
          "Europe/Simferopol",
          "Europe/Skopje",
          "Europe/Sofia",
          "Europe/Stockholm",
          "Europe/Tallinn",
          "Europe/Tirane",
          "Europe/Tiraspol",
          "Europe/Ulyanovsk",
          "Europe/Uzhgorod",
          "Europe/Vaduz",
          "Europe/Vatican",
          "Europe/Vienna",
          "Europe/Vilnius",
          "Europe/Volgograd",
          "Europe/Warsaw",
          "Europe/Zagreb",
          "Europe/Zaporozhye",
          "Europe/Zurich",
          "Factory",
          "GB",
          "GB-Eire",
          "GMT",
          "GMT+0",
          "GMT-0",
          "GMT0",
          "Greenwich",
          "HST",
          "Hongkong",
          "Iceland",
          "Indian/Antananarivo",
          "Indian/Chagos",
          "Indian/Christmas",
          "Indian/Cocos",
          "Indian/Comoro",
          "Indian/Kerguelen",
          "Indian/Mahe",
          "Indian/Maldives",
          "Indian/Mauritius",
          "Indian/Mayotte",
          "Indian/Reunion",
          "Iran",
          "Israel",
          "Jamaica",
          "Japan",
          "Kwajalein",
          "Libya",
          "MET",
          "MST",
          "MST7MDT",
          "Mexico/BajaNorte",
          "Mexico/BajaSur",
          "Mexico/General",
          "NZ",
          "NZ-CHAT",
          "Navajo",
          "PRC",
          "PST8PDT",
          "Pacific/Apia",
          "Pacific/Auckland",
          "Pacific/Bougainville",
          "Pacific/Chatham",
          "Pacific/Chuuk",
          "Pacific/Easter",
          "Pacific/Efate",
          "Pacific/Enderbury",
          "Pacific/Fakaofo",
          "Pacific/Fiji",
          "Pacific/Funafuti",
          "Pacific/Galapagos",
          "Pacific/Gambier",
          "Pacific/Guadalcanal",
          "Pacific/Guam",
          "Pacific/Honolulu",
          "Pacific/Johnston",
          "Pacific/Kanton",
          "Pacific/Kiritimati",
          "Pacific/Kosrae",
          "Pacific/Kwajalein",
          "Pacific/Majuro",
          "Pacific/Marquesas",
          "Pacific/Midway",
          "Pacific/Nauru",
          "Pacific/Niue",
          "Pacific/Norfolk",
          "Pacific/Noumea",
          "Pacific/Pago_Pago",
          "Pacific/Palau",
          "Pacific/Pitcairn",
          "Pacific/Pohnpei",
          "Pacific/Ponape",
          "Pacific/Port_Moresby",
          "Pacific/Rarotonga",
          "Pacific/Saipan",
          "Pacific/Samoa",
          "Pacific/Tahiti",
          "Pacific/Tarawa",
          "Pacific/Tongatapu",
          "Pacific/Truk",
          "Pacific/Wake",
          "Pacific/Wallis",
          "Pacific/Yap",
          "Poland",
          "Portugal",
          "ROC",
          "ROK",
          "Singapore",
          "Turkey",
          "UCT",
          "US/Alaska",
          "US/Aleutian",
          "US/Arizona",
          "US/Central",
          "US/East-Indiana",
          "US/Eastern",
          "US/Hawaii",
          "US/Indiana-Starke",
          "US/Michigan",
          "US/Mountain",
          "US/Pacific",
          "US/Samoa",
          "UTC",
          "Universal",
          "W-SU",
          "WET",
          "Zulu"
        ]
      },
      formState: {
        ready: false,
        dirty: false,
        valid: true,
        readOnly: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      },
      rights: window.$gz.role.defaultRightsObject(),
      timeZoneName: window.$gz.locale.getResolvedTimeZoneName(),
      sockType: window.$gz.type.SubscriptionServer
    };
  },
  watch: {
    formState: {
      handler: function(val) {
        if (this.formState.loading) {
          return;
        }

        if (val.dirty && val.valid && !val.readOnly) {
          window.$gz.eventBus.$emit("menu-enable-item", FORM_KEY + ":save");
        } else {
          window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":save");
        }

        if (!val.dirty && val.valid && !val.readOnly) {
          window.$gz.eventBus.$emit(
            "menu-enable-item",
            FORM_KEY + ":duplicate"
          );
          window.$gz.eventBus.$emit("menu-enable-item", FORM_KEY + ":new");
        } else {
          window.$gz.eventBus.$emit(
            "menu-disable-item",
            FORM_KEY + ":duplicate"
          );
          window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":new");
        }
      },
      deep: true
    }
  },
  async created() {
    const vm = this;
    try {
      await initForm(vm);
      vm.rights = window.$gz.role.getRights(window.$gz.type.SubscriptionServer);
      vm.formState.readOnly = !vm.rights.change;
      window.$gz.eventBus.$on("menu-click", clickHandler);
      //---------------------------------
      let setDirty = false;
      //id 0 means create or duplicate to new
      if (vm.$route.params.recordid != 0) {
        //is there already an obj from a prior operation?
        if (this.$route.params.obj) {
          //yes, no need to fetch it
          this.obj = this.$route.params.obj;
        } else {
          await vm.getDataFromApi(vm.$route.params.recordid);
        }
      } else {
        //Might be a duplicate and contain another record
        if (this.$route.params.obj) {
          this.obj = this.$route.params.obj;
          this.obj.concurrency = undefined;
          this.obj.id = 0;
          this.obj.name = `${this.obj.name} - ${window.$gz.translation.get(
            "Copy"
          )}`;
          setDirty = true;
        }
      }
      window.$gz.form.setFormState({
        vm: vm,
        loading: false,
        dirty: setDirty,
        valid: true
      });
      //----------------------------
      generateMenu(vm);
    } catch (error) {
      window.$gz.errorHandler.handleFormError(error, vm);
    } finally {
      vm.formState.ready = true;
    }
  },
  async beforeRouteLeave(to, from, next) {
    if (!this.formState.dirty || JUST_DELETED) {
      next();
      return;
    }
    if ((await window.$gz.dialog.confirmLeaveUnsaved()) === true) {
      next();
    } else {
      next(false);
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  methods: {
    subExpireAddOneWeek: function() {
      // // eslint-disable-next-line
      // debugger;
      const now = window.$gz.locale.nowUTC8601String(this.timeZoneName);
      this.obj.subscriptionExpire = window.$gz.locale.addDurationToUTC8601String(
        now,
        {
          days: 7
        }
      );
    },
    subExpireAddOneMonth: function() {
      const now = window.$gz.locale.nowUTC8601String(this.timeZoneName);
      this.obj.subscriptionExpire = window.$gz.locale.addDurationToUTC8601String(
        now,
        {
          months: 1
        }
      );
    },
    subExpireAddOneYear: function() {
      const now = window.$gz.locale.nowUTC8601String(this.timeZoneName);
      this.obj.subscriptionExpire = window.$gz.locale.addDurationToUTC8601String(
        now,
        {
          years: 1
        }
      );
    },
    canSave: function() {
      return this.formState.valid && this.formState.dirty;
    },
    canDuplicate: function() {
      return this.formState.valid && !this.formState.dirty;
    },
    sockTypes: function() {
      return window.$gz.type;
    },
    form() {
      return window.$gz.form;
    },
    fieldValueChanged(ref) {
      if (
        this.formState.ready &&
        !this.formState.loading &&
        !this.formState.readOnly
      ) {
        window.$gz.form.fieldValueChanged(this, ref);
      }
    },
    async getDataFromApi(recordId) {
      const vm = this;
      window.$gz.form.setFormState({
        vm: vm,
        loading: true
      });
      if (!recordId) {
        throw new Error(FORM_KEY + "::getDataFromApi -> Missing recordID!");
      }
      try {
        window.$gz.form.deleteAllErrorBoxErrors(vm);
        const res = await window.$gz.api.get(API_BASE_URL + recordId);
        if (res.error) {
          if (res.error.code == "2010") {
            window.$gz.form.handleObjectNotFound(vm);
          }
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          vm.obj = res.data;
          generateMenu(vm);
          window.$gz.form.setFormState({
            vm: vm,
            dirty: false,
            valid: true,
            loading: false
          });
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, vm);
      } finally {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
      }
    },
    async submit() {
      const vm = this;
      if (vm.canSave == false) {
        return;
      }
      try {
        window.$gz.form.setFormState({
          vm: vm,
          loading: true
        });
        window.$gz.form.deleteAllErrorBoxErrors(vm);
        const res = await window.$gz.api.upsert(API_BASE_URL, vm.obj);
        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          if (res.data.id) {
            //POST
            vm.obj = res.data;
            this.$router.replace({
              name: "subscription-server-edit",
              params: {
                recordid: res.data.id,
                obj: res.data
              }
            });
          } else {
            //PUT
            vm.obj.concurrency = res.data.concurrency;
          }
          window.$gz.form.setFormState({
            vm: vm,
            dirty: false,
            valid: true
          });
        }
      } catch (ex) {
        window.$gz.errorHandler.handleFormError(ex, vm);
      } finally {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
      }
    },
    async remove() {
      try {
        const dialogResult = await window.$gz.dialog.confirmDelete();
        if (dialogResult != true) {
          return;
        }
        window.$gz.form.setFormState({
          vm: this,
          loading: true
        });

        if (this.$route.params.recordid == 0) {
          JUST_DELETED = true;

          this.$router.go(-1);
        } else {
          window.$gz.form.deleteAllErrorBoxErrors(this);
          const res = await window.$gz.api.remove(
            API_BASE_URL + this.$route.params.recordid
          );
          if (res.error) {
            this.formState.serverError = res.error;
            window.$gz.form.setErrorBoxErrors(this);
          } else {
            JUST_DELETED = true;
            this.$router.go(-1);
          }
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, this);
      } finally {
        window.$gz.form.setFormState({
          vm: this,
          loading: false
        });
      }
    },
    duplicate() {
      this.$router.push({
        name: "subscription-server-edit",
        params: {
          recordid: 0,
          obj: this.obj
        }
      });
    }
  }
};

/////////////////////////////
//
//
async function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  const m = window.$gz.menu.parseMenuItem(menuItem);
  if (m.owner == FORM_KEY && !m.disabled) {
    switch (m.key) {
      case "save":
        m.vm.submit();
        break;
      case "delete":
        m.vm.remove();
        break;
      case "new":
        m.vm.$router.push({
          name: "subscription-server-edit",
          params: { recordid: 0 }
        });
        break;
      case "duplicate":
        m.vm.duplicate();
        break;
      case "report":
        {
          const res = await m.vm.$refs.reportSelector.open(
            {
              AType: window.$gz.type.SubscriptionServer,
              selectedRowIds: [m.vm.obj.id]
            },
            m.id
          );
          if (res == null) {
            return;
          }
          window.$gz.form.setLastReportMenuItem(FORM_KEY, res, m.vm);
        }
        break;
      // case "terminal":
      //   alert("putty -agent -ssh sportseffect.onayanova.com");
      //   break;
      case "QuoteList":
        m.vm.$router.push({
          name: "svc-quotes",
          params: {
            aType: m.vm.sockType,
            objectId: m.vm.obj.id,
            name: m.vm.obj.name
          }
        });
        break;
      case "PMList":
        m.vm.$router.push({
          name: "svc-pms",
          params: {
            aType: m.vm.sockType,
            objectId: m.vm.obj.id,
            name: m.vm.obj.name
          }
        });
        break;
      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

//////////////////////
//
//
function generateMenu(vm) {
  const menuOptions = {
    isMain: false,
    readOnly: vm.formState.readOnly,
    icon: "$sockiCloud",
    title: "SubscriptionServer",
    formData: {
      sockType: window.$gz.type.SubscriptionServer,
      recordId: vm.$route.params.recordid,
      formCustomTemplateKey: FORM_CUSTOM_TEMPLATE_KEY,
      recordName: vm.obj.name
    },
    menuItems: []
  };

  if (vm.rights.change) {
    menuOptions.menuItems.push({
      title: "Save",
      icon: "$sockiSave",
      surface: true,
      key: FORM_KEY + ":save",
      vm: vm
    });
  }

  menuOptions.menuItems.push({
    title: "Report",
    icon: "$sockiFileAlt",
    key: FORM_KEY + ":report",
    vm: vm
  });

  const lastReport = window.$gz.form.getLastReport(FORM_KEY);
  if (lastReport != null) {
    menuOptions.menuItems.push({
      title: lastReport.name,
      notrans: true,
      icon: "$sockiFileAlt",
      key: FORM_KEY + ":report:" + lastReport.id,
      vm: vm
    });
  }

  if (vm.rights.change) {
    menuOptions.menuItems.push({
      title: "New",
      icon: "$sockiPlus",
      key: FORM_KEY + ":new",
      vm: vm
    });
  }

  if (vm.rights.change && vm.$route.params.recordid != 0) {
    menuOptions.menuItems.push({
      title: "Duplicate",
      icon: "$sockiClone",
      key: FORM_KEY + ":duplicate",
      vm: vm
    });
  }
  if (vm.rights.delete && vm.$route.params.recordid != 0) {
    menuOptions.menuItems.push({
      title: "Delete",
      icon: "$sockiTrashAlt",
      surface: false,
      key: FORM_KEY + ":delete",
      vm: vm
    });
  }
  menuOptions.menuItems.push({ divider: true, inset: false });

  // menuOptions.menuItems.push({
  //   title: "OpenTerminal",
  //   icon: "$sockiTerminal",
  //   key: FORM_KEY + ":terminal",
  //   vm: vm
  // });

  //   menuOptions.menuItems.push({
  //     title: "QuoteList",
  //     icon: "$sockiPencilAlt",
  //     key: FORM_KEY + ":QuoteList",
  //     vm: vm
  //   });

  //   menuOptions.menuItems.push({
  //     title: "PMList",
  //     icon: "$sockiBusinessTime",
  //     key: FORM_KEY + ":PMList",
  //     vm: vm
  //   });

  menuOptions.menuItems.push({ divider: true, inset: false });
  window.$gz.eventBus.$emit("menu-change", menuOptions);
}

let JUST_DELETED = false;

/////////////////////////////////
//
//
async function initForm(vm) {
  await fetchTranslatedText();
  await window.$gz.formCustomTemplate.get(FORM_CUSTOM_TEMPLATE_KEY, vm);
  await populateSelectionLists(vm);
}

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText() {
  await window.$gz.translation.cacheTranslations([
    "SubscriptionServer",
    "SubServerName",
    "Customer",
    "SubServerNotes",
    "Created",
    "SubServerDatacenter",
    "SubServerTimeZone",
    "DatabaseID",
    "SubServerLastUpdated",
    "SubServerSubExpire",
    "SubServerLastHealthStatus",
    "SubServerLastHealthCheck",
    "SubServerTrial",
    "SubServerTrialContact",
    "SubServerTrialEmail",
    "SubServerTrialCompany",
    "SubServerOperatingSystem",
    "SubServerCustomerDomain",
    "LoanUnitRateMonthCost",
    "SubServerIP",
    "ServerState"
  ]);
}

//////////////////////
//
//
async function populateSelectionLists(vm) {
  //ensure the pick lists required are pre-fetched
  await window.$gz.enums.fetchEnumList("ServerState");
  vm.selectLists.serverStates = window.$gz.enums.getSelectionList(
    "ServerState"
  );
}
</script>
