// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

/**
 * This controller implements the application logic of the DHL tab that
 * is part of the order detail window. It also handles the event that
 * is fired when clicking the 'Add label' icon in the order list view to
 * directly access the DHL tab.
 */
// {namespace name="backend/viison_dhl_order/order"}
Ext.define('Shopware.apps.ViisonDHLOrder.controller.Tab', {

    /**
     * Extend the order tab controller from the ShippingCommon module
     */
    extend: 'Shopware.apps.ViisonShippingCommonOrder.controller.Tab',

    /**
     * Plugin-specific properties required by the parent class
     */
    dispatchServiceProviderPrefix: 'ViisonDHL',
    dispatchServiceProviderPanelClass: 'order-viison-dhl-tab',
    productStoreClass: 'Shopware.apps.ViisonDHLShipping.store.Product',
    labelConfirmPanelClass: 'Shopware.apps.ViisonDHLOrder.view.detail.LabelConfirm',
    shippingLabelClass: 'Shopware.apps.ViisonDHLOrder.model.ShippingLabel',
    sendMailURL: '{url controller="ViisonDHLOrder" action="sendMail"}',
    downloadDocumentsURL: '{url controller="ViisonDHLOrder" action="downloadDocuments"}',
    calculateShippingWeightURL: '{url controller="ViisonDHLOrder" action="calculateShippingWeight"}',
    getShippingOrderDataURL: '{url controller="ViisonDHLOrder" action="getShippingOrderData"}',
    dispatchServiceProviderCSSClass: Ext.baseCSSPrefix + 'dhl',
    dispatchServiceProviderLabelConfirmPanel: 'order-viison-dhl-label-confirm-panel',
    listDispatchActionsControllerClass: 'Shopware.apps.ViisonDHLOrder.controller.ListDispatchActions',
    labelConfirmWindow: 'Shopware.apps.ViisonDHLOrder.view.detail.LabelConfirmWindow', // @override because we added a new Store for time frame
    orderConfigDataClass: 'Shopware.apps.ViisonDHLOrder.store.OrderConfigData',

    /**
     * @Override
     *
     * Additional properties required by the parent class.
     */
    mergedLabelsFromOrderActionUrl: '{url controller="ViisonDHLOrder" action="getMergedLabelsForOrder"}',

    /**
     * The maximum number of shipping labels per order. TODO Interesting approach, keep it as a reference for letter
     */
    maxNumberOfLabels: Ext.JSON.decode('{$pluginInfo->getMaxLabels()}'),

    loadDataForOrder: function (record) {
        var me = this;
        me.callParent(arguments);
        me.loadShopwareDHLIntegrationData(record);
    },

    /**
     * Loads the post number from the Shopware DHL integration if that plugin is installed and the
     * user chose Packstation or Postfiliale in the checkout.
     *
     * @param record The record representing the order.
     */
    loadShopwareDHLIntegrationData: function (record) {
        var me = this;
        Ext.Ajax.request({
            url: '{url controller="ViisonDHLOrder" action="getShopwareDHLIntegrationData"}',
            params: {
                orderId: record.getId(),
            },
            success: function (response) {
                var data = Ext.JSON.decode(response.responseText).data;
                record[me.dispatchServiceProviderPrefix] = record[me.dispatchServiceProviderPrefix] || {};
                record[me.dispatchServiceProviderPrefix].postNumber = data.postNumber;
                if (me.getLabelConfirmWindow() && me.getLabelConfirmWindow().dataPanel) {
                    // Force update of displayed values in label confirm view
                    me.getLabelConfirmWindow().dataPanel.setValues();
                }
            },
        });
    },

    /**
     * Set the default personal handover setting when opening the label confirm window
     *
     * @override
     * @param dispatchServiceProviderTab
     * @param record
     * @param shippingLabelStore
     */
    onShowLabelConfirmWindow: function (dispatchServiceProviderTab, record) {
        this.callParent(arguments);

        this.updateServiceOptions(record);
    },

    /**
     * Loads the default settings for service options from the backend controller. If already a label
     * confirm window and panel exist, it will be updated.
     *
     * @param record The record representing the order.
     */
    updateServiceOptions: function (record) {
        var me = this;
        Ext.Ajax.request({
            url: '{url controller="ViisonDHLOrder" action="getDefaultServiceOptions"}',
            params: {
                orderId: record.getId(),
            },
            success: function (response) {
                var data = Ext.JSON.decode(response.responseText);

                if (me.getLabelConfirmWindow() && me.getLabelConfirmWindow().dataPanel) {
                    me.getLabelConfirmPanel().endorsementType = data.endorsementType;
                    me.getLabelConfirmPanel().parcelOutletRouting = data.parcelOutletRouting;
                    me.getLabelConfirmPanel().defaultMinimumAge = data.minimumAge;
                    me.getLabelConfirmPanel().personalHandover = data.personalHandover;
                    me.getLabelConfirmPanel().defaultIdentCheckAge = data.identCheckAge;
                    me.getLabelConfirmPanel().postalDeliveryDutyPaid = data.postalDeliveryDutyPaid;
                    me.getLabelConfirmPanel().closestDroppointDelivery = data.closestDroppointDelivery;
                    me.getLabelConfirmPanel().signedForByRecipient = data.signedForByRecipient;
                    // Force update of displayed values in label confirm view
                    me.getLabelConfirmWindow().dataPanel.setValues();
                }
            },
        });
    },

    /**
     * @override
     */
    handleCustomShippingOrderData: function (record, data) {
        var me = this;
        record[me.dispatchServiceProviderPrefix].defaultDayOfDelivery = data.defaultDayOfDelivery;
    },

});
