<?php

namespace Webkul\WooCommerceBundle\Controller\Rest;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Oro\Bundle\SecurityBundle\Annotation\AclAncestor;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Optional;
use Symfony\Component\Validator\Constraints\Url;
use Symfony\Component\Form\FormError;
use Oro\Bundle\ConfigBundle\Entity\ConfigValue;
use Symfony\Component\Intl\Intl;
use Akeneo\Component\Batch\Model\JobInstance;
use Akeneo\Tool\Component\Batch\Model\JobInstance as jobinstance2;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Webkul\WooCommerceBundle\Services\WooCommerceConnector;
use Webkul\WooCommerceBundle\Entity\CredentialConfig;


/**
 * Configuration rest controller in charge of the woocommerce connector configuration managements
 */
class ConfigurationController extends Controller
{
    const SECTION = 'woocommerce_connector';

    const MAPPING_SECTION = 'woccomerce_store_mapping';
    const DEFAULTS_SECTION = 'woocommerce_connector_defaults';
    const QUICKSETTING_SECTION = "woocommerce_quicksettings";
    const OTHER_MAPPING_SECTION = 'woocommerce_other_mappings';
    const OTHER_MAPPING = 'woocommerce_connector_othermapping';
    const SECTION_ASSOCIATION_ATTRIBUTE_MAPPING = 'woocommerce_association_mapping';
    const MAIN_LOCALE = 'en';

    const QUICK_EXPORT_CODE = 'woocommerce_quick_export';


    protected $connectorService;
    protected $currencyRepo;
    protected $localeRepo;
    protected $jobInstanceRepo;



    public function __construct(
        $connectorService, 
        $currencyRepo, 
        $localeRepo,
        $jobInstanceRepo

        ) {
        $this->connectorService = $connectorService;
        $this->currencyRepo = $currencyRepo;
        $this->localeRepo = $localeRepo;
        $this->jobInstanceRepo = $jobInstanceRepo;
    }


    /**
     * Get the current configuration
     *
     * * @AclAncestor("webkul_akeneo_woocommerce_connector_configuration")
     *
     * @return JsonResponse
     */
    public function getAction()
    {
        $connectorService = $this->get('woocommerce.connector.service');
        
        $data = $connectorService->getCredentials();
        $data['settings'] = $connectorService->getSettings();
        $data['defaults'] = $connectorService->getSettings(self::DEFAULTS_SECTION);
        $data['quicksettings'] = $connectorService->getSettings(self::QUICKSETTING_SECTION);
        $data['other_mappings'] = $connectorService->getOtherMappings();
        $data['othermapping'] = $connectorService->getSettings(self::OTHER_MAPPING);
        if ($associationMapping = $connectorService->getSettings(self::SECTION_ASSOCIATION_ATTRIBUTE_MAPPING)) {
            $data['association'] = $associationMapping;
        }
        return new JsonResponse($data);
    }

    /**
     * Get the current configuration
     *
     * * @AclAncestor("webkul_akeneo_woocommerce_connector_configuration")
     *
     * @return JsonResponse
     */
    


    public function postAction(Request $request)
    { 
        $data  = [];
        $params = $request->request->all();
       
        $connectorService = $this->get('woocommerce.connector.service');
        $em = $this->getDoctrine()->getManager();
        if ($request->getMethod() == 'POST') {
            if (isset($params['other_mappings'])) {
                $connectorService->saveSettings($params['other_mappings'], self::OTHER_MAPPING_SECTION);
            }

            if (isset($params['quicksettings'])) {
                $connectorService->saveSettings($params['quicksettings'], self::QUICKSETTING_SECTION);
            }

            if (isset($params['association'])) {
                $connectorService->saveSettings($params['association'], self::SECTION_ASSOCIATION_ATTRIBUTE_MAPPING);
            }

            if (isset($params['othermapping'])) {
                $connectorService->saveSettings($params['othermapping'], self::OTHER_MAPPING);
            }

            if ('settings' === $request->attributes->get('tab')) {
                if (!empty($params['settings'])) {
                    $connectorService->saveSettings($params['settings']);
                }

                if (isset($params['defaults'])) {
                    $connectorService->saveSettings($params['defaults'], self::DEFAULTS_SECTION);
                }
            } else {
                $form = $this->getConfigForm();
                $form->submit($params);
                
                // if ($params['consumerSecret'] === str_repeat('*', 20)) {
                //     $data = $this->connectorService->getAllCredentials($params['id']);
                //     $params['consumerSecret'] = $data['consumerSecret'];
                // } 
                                       
                             
               // if ($form->isValid() && $connectorService->checkCredentials($params)) {
                    
                    $connectorService->saveCredentials($params);
                // } else {
                //     $form->get('consumerSecret')->addError(new FormError('invalid details'));
                //     return new JsonResponse($this->getFormErrors($form), Response::HTTP_BAD_REQUEST);
                // }
            }
            $this->checkAndSaveQuickJob();
        }
        
        return $this->getAction();
    }


    protected function checkAndSaveQuickJob()
    {
        $jobInstance = $this->jobInstanceRepo->findOneBy(['code' => self::QUICK_EXPORT_CODE]);
    
        if (!$jobInstance) {
            $em = $this->getDoctrine()->getManager();
        
            if (class_exists('Akeneo\Component\Batch\Model\JobInstance')) {
                $jobInstance = new JobInstance();
            } else {
                $jobInstance = new JobInstance2();
            }
            $jobInstance->setCode(self::QUICK_EXPORT_CODE);
            $jobInstance->setJobName('woocommerce_quick_export');
            $jobInstance->setLabel('Woocommerce quick export');
            $jobInstance->setConnector('Woocommerce Export Connector');
            $jobInstance->setType('quick_export');
            $em->persist($jobInstance);
            $em->flush();
        }
    }

    public function getDataAction()
    {
        return new JsonResponse($this->mappingFields);
    }

    public function getData2Action()
    {
        $currencies = [];
        $connectorService = $this->get('woocommerce.connector.service');
        $repo = $connectorService->getPimRepository('currency');
        $codes = $repo->getActivatedCurrencyCodes();
        
        
        foreach (Intl::getCurrencyBundle()->getCurrencyNames() as $currencyCode => $currencyName) {
            foreach ($codes as $code) {
                if ($currencyCode == $code) {
                    $currencies[$currencyCode] = $currencyName;
                }
            }
        }
        
        return new JsonResponse($currencies);
    }

    public function getCurrenciesAction()
    {
        $currencies = [];
        $connectorService = $this->get('woocommerce.connector.service');
        $repo = $connectorService->getPimRepository('currency');
        $codes = $repo->getActivatedCurrencyCodes();
        
        foreach (Intl::getCurrencyBundle()->getCurrencyNames() as $currencyCode => $currencyName) {
            $currencies[$currencyCode] = $currencyName;
        }
        return new JsonResponse($currencies);
    }

    // Add History Tab
    public function getHistoryClassAction(Request $request)
    {
        if (!$request->isXmlHttpRequest()) {
            return new RedirectResponse('/');
        }

        $version = new \AkeneoVersion();
        $historyClass = 'Akeneo\Component\Batch\Model\JobInstance';

        if ($version::VERSION >= '3.0') {
            $historyClass = 'Akeneo\Tool\Component\Batch\Model\JobInstance';
        }
        return new JsonResponse(['history_class'=> $historyClass]);
    }

    public function getLocalesAction()
    {
        $locales = [];
        $fallbackLocales = $this->get('translator')->getFallbackLocales();
        $localeNames = Intl::getLocaleBundle()->getLocaleNames(self::MAIN_LOCALE);

        foreach ($localeNames as $code => $locale) {
            $locales[$code] = $locale;
        }
        
        return new JsonResponse($locales);
    }

    // to fetch active currencies
    public function getActiveCurrenciesAction()
    {
        $currencies = [];
        $connectorService = $this->get('woocommerce.connector.service');
        
        $repo = $connectorService->getPimRepository('currency');
        
        $codes = $repo->getActivatedCurrencyCodes();
        foreach ($codes as $code) {
            $currencies[$code] = Intl::getCurrencyBundle()->getCurrencyName($code);
        }
        
        return new JsonResponse($currencies);
    }

    public function getLocaleListAction(Request $request)
    {
        $locales = [];
        if (class_exists('Webkul\WpmlProductBundle\Connector\Writer\Product')) {
            $data = $this->localeRepo;

            $codes = $data->getActivatedLocalesQB()->getQuery()->getArrayResult();

            foreach ($codes as $code) {
                if (is_array($code)) {
                    $code = $code['code'];
                }

                $locales[$code] = Intl::getLocaleBundle()->getLocaleName($code);
            }

            return new JsonResponse($locales);
        } else {
            return new JsonResponse($locales);
        }
    }

    private function getConfigForm() 
    {
        $form = $this->createFormBuilder(null, [
                    'allow_extra_fields' => true,
                    'csrf_protection' => false
                ]);
        $form->add('shopUrl', null, [
            'constraints' => [
                new Url(),
                new NotBlank()                
            ]
        ]);
        $form->add('consumerKey', null, [
            'constraints' => [
                new NotBlank()
            ]
        ]);
        $form->add('consumerSecret', null, [
            'constraints' => [
                new NotBlank()
            ]
        ]);                   

        return $form->getForm();
    }

    private function getFormErrors($form)
    {
        
        $errorContext = [];
        foreach ($form->getErrors(true) as $key => $error) {
            $errorContext[$error->getOrigin()->getName()] = $error->getMessage();
        }

        return $errorContext;
    }

    public function checkWpmlStatusAction()
    {
        $classex = 'Webkul\WpmlProductBundle\Connector\Writer\Product';
        $wpmlStatus = false;
        if(!isset($settings)){
            $settings = $this->connectorService->getSettings('settings');
        }
        if (class_exists($classex) && $settings['enable_wpml'] == "on") {
            $connectorService = $this->get('woocommerce.connector.service');
            $getData = $connectorService->getSettings();
            $wpmlStatus = isset($getData['enable_wpml']) && $getData['enable_wpml'] == 'on' ? true  : false;
        }
        
        return new JsonResponse($wpmlStatus);
    }

    private $mappingFields = [
        [
            'name' => 'slug',
            'label' => 'woocommerce.useas.slug',
            'types' => [
                'pim_catalog_text',

            ],
            'tooltip' => 'supported attributes types: text',
        ],
        [
            'name' => 'name',
            'label' => 'woocommerce.useas.name',
            'types' => [
                'pim_catalog_text',
            ],
            'tooltip' => 'supported attributes types: text',
        ],
        [
            'name' => 'regular_price',
            'label' => 'woocommerce.useas.price',
            'types' => [
                'pim_catalog_price_collection',
                // 'pim_catalog_number',
            ],
            'tooltip' => 'supported attributes types: price',
        ],
        [
            'name' => 'weight',
            'label' => 'woocommerce.useas.weight',
            'types' => [
                'pim_catalog_metric',
                'pim_catalog_number',
            ],
            'tooltip' => 'supported attributes types: number, metric',
        ],
        [
            'name' => 'length',
            'label' => 'woocommerce.useas.length',
            'types' => [
                'pim_catalog_metric',
                'pim_catalog_number',
            ],
            'tooltip' => 'supported attributes types: number, metric',
        ],
        [
            'name' => 'width',
            'label' => 'woocommerce.useas.breadth',
            'types' => [
                'pim_catalog_metric',
                'pim_catalog_number',
            ],
            'tooltip' => 'supported attributes types: number, metric',
        ],
        [
            'name' => 'height',
            'label' => 'woocommerce.useas.height',
            'types' => [
                'pim_catalog_metric',
                'pim_catalog_number',
            ],
            'tooltip' => 'supported attributes types: number, metric',
        ],
        [
            'name' => 'description',
            'label' => 'woocommerce.useas.description',
            'types' => [
                'pim_catalog_text',
                'pim_catalog_textarea',
            ],
            'tooltip' => 'supported attributes types: text, textarea (even rich content)',
        ],
        [
            'name' => 'short_description',
            'label' => 'woocommerce.useas.short_description',
            'types' => [
                'pim_catalog_text',
                'pim_catalog_textarea',
            ],
            'tooltip' => 'supported attributes types: text, textarea',
        ],
        [
            'name' => 'stock_quantity',
            'label' => 'woocommerce.useas.quantity',
            'types' => [
                'pim_catalog_number',
            ],
            'tooltip' => 'supported attributes types: number',
        ],
        [
            'name' => 'featured',
            'label' => 'woocommerce.useas.featured',
            'types' => [
                'pim_catalog_boolean',
            ],
            'tooltip' => 'supported attributes types: boolean',
        ],
        [
            'name' => 'purchase_note',
            'label' => 'woocommerce.useas.purchase_note',
            'types' => [
                'pim_catalog_text',
                'pim_catalog_simpleselect',
            ],
            'tooltip' => 'supported attributes types: text, simple select',
        ],
        [
            'name' => 'reviews_allowed',
            'label' => 'woocommerce.useas.reviews_allowed',
            'types' => [
                'pim_catalog_boolean',
            ],
            'tooltip' => 'supported attributes types: boolean',
        ],
        [
            'name' => 'backorders_allowed',
            'label' => 'woocommerce.useas.backorders_allowed',
            'types' => [
                'pim_catalog_boolean',
            ],
            'tooltip' => 'supported attributes types: boolean',
        ],
        // [
        //     'name' => 'sale_price',
        //     'label' => 'woocommerce.useas.sale_price',
        //     'types' => [
        //         'pim_catalog_price_collection',
        //     ],
        //     'tooltip' => 'supported attributes types: price',
        // ],
    ];
}
