<?php
/**
 * Copyright (c) 2016 Serhii Borodai <clarifying@gmail.com>.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 *
 */

namespace App\Model;

use App\Entity\Zone;
use Zend\Diactoros\Response\JsonResponse;

/**
 * Class Zones
 * @package App\Model
 */
class Zones extends Common
{

    /**
     * @param $id
     * @return Zone[]
     */
    public function findBySiteId($id)
    {
        /** @noinspection PhpIncompatibleReturnTypeInspection */
        return $this->findAll(['site_id' => $id, 'hidden' => 0]);
    }
    
    /**
     * @param $id
     * @return int
     */
    public function findCurrentIdBySiteId($id)
    {
        /** @noinspection PhpIncompatibleReturnTypeInspection */
        $zones = $this->findAll(['site_id' => $id]);
        $currentIdZone = $id * 100;
        foreach ($zones as $zone) {
            $currentIdZone = ($zone->getId() > $currentIdZone) ? $zone->getId(): $currentIdZone;
        }
        return $currentIdZone;
    }
    
    public function findSiteZones()
    {
        $adapter = $this->tableGateway->getAdapter();
        
        $sql = 'SELECT site_id, COUNT(*) AS count'
                . ' FROM ' . (string) $this->tableGateway->getTable() 
                . ' GROUP BY site_id';
        $res = $adapter->query($sql, \Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE);
        
        $zonesCount = array();
        if($res) {
            foreach($res as $r) {
                $zonesCount[$r['site_id']] = $r['count'];                
            }
        }

        return $zonesCount;
    }
    
    public function findZonesInfoSize()
    {
        $zones_list = [];
        $zones = $this->findAll()->toArray();
        foreach ($zones as $zone) {
            $zones_list[$zone['id']]['size'] = $zone['width'].'x'.$zone['height'];
            $zones_list[$zone['id']]['site_id'] = $zone['site_id'];
        }
        return $zones_list;
    }
    
    public function findZonesInfoSizeById($zones_id)
    {
        $zones_list = [];
        $zones = $this->findAll(['id' => $zones_id])->toArray();
        foreach ($zones as $zone) {
            $zones_list[$zone['id']]['size'] = $zone['width'].'x'.$zone['height'];
        }
        return $zones_list;
    }


    /**
     * @param \App\Entity\Common $entity
     * @return int
     * @throws \Exception
     */
    public function create($entity)
    {
        
        $data = $this->delegatingHydrator->extract($entity);
        
        // accept data columns only available at table
        $data = array_intersect_key($data, array_fill_keys($this->tableGateway->getColumns(), 1));

        $query = function($data) {
            $this->tableGateway->insert($data);
            $insertId = $this->tableGateway->lastInsertValue;
            return $insertId;
        };

        try {
            $this->tableGateway->getAdapter()->getDriver()->getConnection()->beginTransaction();
            $id = $query($data);
            $this->tableGateway->getAdapter()->getDriver()->getConnection()->commit();
        } catch (\Exception $e) {
            $this->tableGateway->getAdapter()->getDriver()->getConnection()->rollback();
            throw $e;
        }
        return $id;
    }

    public function updateStatus($id, $status, $value)
    {
        $zone = $this->findById($id);
        
        $data = [];
        if ($zone) {
            
            $hydrator = $this->delegatingHydrator;
            $zone = $hydrator->hydrate([$status => $value], $zone);
            
            try {
                $this->save($zone);
                $data['result'] = true;
            } catch (\Exception $e) {
                $data['result'] = false;
                $data['msg'] = $e->getMessage();
            }
        } else {
            $data = [
                'result' => false,
                'msg' => 'Zone not found',
            ];
        }
        
        $response = new JsonResponse($data);
        return $response;
    }
 
    public function deleteBySiteId($site_id)
    {
        $zone_items = $this->findAll(['site_id' => $site_id]);
        if ($zone_items)
        {
            foreach ($zone_items as $zone_item)
            {
                $result = $this->deleteById($zone_item->getId());
            }
        }
        return $result;
    }
    
    public function createListZones()
    {
        $list_zones = [];
        foreach($this->findAll()->toArray() as $zone_data) {
            $list_zones[$zone_data['id']] = $zone_data['site_id'];
        }
        return $list_zones;
    }
}