<?php

/**
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is protected by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2018 Lifestyle Webconsulting GmbH
 * @version    $Id:$
 * @link       http://www.life-style.de
 */

namespace Sso\ApiBundle\Api\Importer;

use Sso\ApiBundle\Api;
use Sso\ApiBundle\Database\Webservice;
// Excel reader
use Ddeboer\DataImport\Reader\ExcelReader;
use Sso\ApiBundle\Entity\Webservice\Type\Location as ModelLocation;
use Sso\ApiBundle\Entity\Webservice\Type\Application as ModelApplication;
use LifeStyle\Tools\ORMHelperBundle\Helper as LifeStyleORMHelper;

/**
 * Class Index
 * @package Sso\ApiBundle\Api\Importer
 */
class Index
{
    /**
     * @var Api\Manager
     */
    protected $apiM;

    /**
     * db manager webservice
     * connection
     *
     * @var Webservice\Manager
     */
    protected $dbManWs;

    /**
     *
     * @var int
     */
    protected $importInsert;

    /**
     *
     * @var int
     */
    protected $importError;

    /**
     *
     * @var int
     */
    protected $importUpdate;

    /**
     * Constructor
     *
     * @param Api\Manager $apiM
     */
    public function __construct(Api\Manager $apiM)
    {
        $this->apiM = $apiM;
        $this->dbManWs = $this->apiM->database()->webservice();
        $this->importError = 0;
        $this->importInsert = 0;
        $this->importUpdate = 0;
    }

    /**
     *
     * @param type $fullFilePath
     */
    public function importLocationsFromXls($fullFilePath)
    {
        set_time_limit(120);

        $file = new \SplFileObject($fullFilePath);
        $reader = new ExcelReader($file);
        $reader->setHeaderRowNumber(0);

        $countAll = 0;
        $countInsert = 0;


        foreach ($reader as $row) {
            $countAll++;
            $typeLocation = $this->fillLocationsModel($row);
            try {
                $insert = $this->dbManWs->location()->saveLocation($typeLocation);
            } catch (\Exception $exc) {
                $this->importError++;
            }
        }

        return array('insert' => $this->importInsert, 'update' => $this->importUpdate, 'error' => $this->importError);

    }

    /**
     *
     * @param array $row
     * @return ModelLocation
     */
    protected function fillLocationsModel(array $row)
    {


        $country = $this->dbManWs->country()->getCountryRepository()->findOneBy(array('code' => $row['country']));
        $timezone = $this->dbManWs->timezone()->getTimezoneRepository()->findOneBy(array('countryCode' => $row['country']));
        //$this->apiM

        if (empty($timezone) || empty($country)) {
            $country = $this->dbManWs->country()->getCountryRepository()->findOneBy(array('code' => 'EN'));
            $timezone = $this->dbManWs->timezone()->getTimezoneRepository()->findOneBy(array('countryCode' => 'EN'));
        }

        //first we check for existing location
        if (isset($row['lcid'])) {
            $searchLocation = array('lcId' => $row['lcid']);
            $locationType = $this->dbManWs->location()->getLocationRepository()->findOneBy($searchLocation);
        }

        if (!$locationType) {
            $locationType = $this->apiM->database()->webservice()->location()->getLocationEntity();
            $locationType->setGuid($this->generateGuid());
            $locationType->setLcId($row['lcid']);
            $this->importInsert++;
        } else {
            $this->importUpdate++;
        }

        $locationType->setCompanyName($row['companyName']);
        $locationType->setLocationName($row['name']);
        $locationType->setStreet($row['street']);
        $locationType->setZip($row['zipCode']);
        $locationType->setCity($row['city']);
        $locationType->setTelephone($row['telephone']);
        $locationType->setFax($row['fax']);
        $locationType->setEmail($row['email']);
        $locationType->setUrl($row['url']);
        $locationType->setUnitType($row['unitType']);
        $locationType->setMetroArea($row['metroArea']);
        $locationType->setIsWebunit($row['isWebUnit']);
        $locationType->setActive($row['isActive']);
        $locationType->setCountry($country);
        $locationType->setTimezone($timezone);

        return $locationType;
    }

    /**
     * @return string
     */
    protected function generateGuid()
    {
        $guidHelper = new LifeStyleORMHelper\GuidGenerator();
        return $guidHelper->getGUID();
    }
}
