<?php

/**
 * This is the model class for table "{{vendor_normalized}}".
 *
 * The followings are the available columns in table '{{vendor_normalized}}':
 * @property integer $id
 * @property integer $status
 * @property integer $type
 * @property string $date_initialized
 * @property string $date_updated
 *
 * The followings are the available model relations:
 * @property CronProductActionProductList $cronProductActionProductList
 */
class CronProductActionStatus extends CActiveRecord
{
	const STATUS_NOT_RUNNING = 0;
	const STATUS_IN_PROGRESS = 1;
	const STATUS_COMPLETED = 2;
	const STATUS_ERROR = 3;

	const TYPE_SET_EOL = 1;
	const TYPE_SET_NOT_EOL = 2;
	const TYPE_RE_PUBLISH = 3;
	const TYPE_OVERWRITE = 4;
	const TYPE_DELETE = 5;
	const TYPE_PRICE_SETTING = 6;
	const TYPE_SYNC_GOOGLE_PRODUCT_IMAGE = 7;


	/* 	new, updated, deleted, remain*/
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{cron_product_action_status}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('status, type', 'required'),
			array('status, type', 'numerical', 'integerOnly'=>true),
			array('date_initialized, date_updated', 'safe'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, status, type, date_initialized, date_updated', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'actionProductList' => array(self::HAS_MANY, 'CronProductActionProductList', 'action_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'status' => 'Status',
			'type' => 'Type',
			'date_initialized' => 'Date Initialized',
			'date_updated' => 'Date Updated',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('status',$this->status);
		$criteria->compare('type',$this->type);
		$criteria->compare('date_initialized',$this->date_initialized,true);
		$criteria->compare('date_updated',$this->date_updated,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return VendorNormalized the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	public function beforeSave() {
		if (parent::beforeSave()) {
			if ($this->isNewRecord) {
				$this->date_initialized = date('Y-m-d H:i:s');
				$this->date_updated = date('Y-m-d H:i:s');
			} else {
				$this->date_updated = date('Y-m-d H:i:s');
			}
		}

		return true;
	}

	public static function createNewCronProductAction($type,$productIds){
		//$transaction = Yii::app()->db->beginTransaction();
		$cron = New CronProductActionStatus;
		$cron->type = $type;
		$cron->status =  self::STATUS_IN_PROGRESS;
		$error = 0;
		if($cron->save(false)){
			foreach ($productIds as $productId) {
				$cronProductList = New CronProductActionProductList;
				$cronProductList->action_id = $cron->id;
				$cronProductList->product_id = $productId;
				$cronProductList->status = CronProductActionProductList::STATUS_PENDING;
				if(!$cronProductList->save(false)){
					//$transaction->commit();
					$error++;
				}
			}
		}else{
			return false;
		}
		if($error > 0){
			return false;
		}else{
			return true;
		}
	}

	public function setStatusCompleted(){
		$this->status = self::STATUS_COMPLETED;
		$this->save(false);
	}

	public function setStatusNotRunning(){
		$this->status = self::STATUS_NOT_RUNNING;
		if($this->save(false)){
			return true;
		}else{
			return false;
		}
	}

	/*public static function getStatusList($withColor = false) {
		if ($withColor) {
			return array(
				self::STATUS_FOR_REVIEW => '<span class="label label-info">For Review</span>',
				self::STATUS_PUSHING => '<span class="label label-warning">Publishing</span>',
				self::STATUS_PUSHED => '<span class="label label-success">Published</span>',
				self::STATUS_ERROR_PUSHING => '<span class="label label-danger">Error Publishing</span>',
				self::STATUS_DELETED => '<span class="label label-danger">Deleted</span>',
				self::STATUS_ERROR_VALIDATION => '<span class="label label-danger">Error Validation</span>',
				self::STATUS_ERROR => '<span class="label label-danger">Errors</span>',
			);
		} else {
			return array(
				self::STATUS_FOR_REVIEW => 'For Review',
				self::STATUS_PUSHING => 'Publishing',
				self::STATUS_PUSHED => 'Published',
				self::STATUS_ERROR_PUSHING => 'Error',
				self::STATUS_DELETED => 'Deleted',
				self::STATUS_ERROR_VALIDATION => 'Error Validation',
				self::STATUS_ERROR => 'Errors'
			);
		}
	}


	public static function getStatusListEdit() {
		return array(
			self::STATUS_FOR_REVIEW => 'Active',
			self::STATUS_DELETED => 'Deleted'
		);
	}

	public static function getStatusLabelWithColor($index) {
		return self::getStatusList(true)[$index];
	}

	public static function getStatusLabel($index) {
		return self::getStatusList(false)[$index];
	}

	public static function countTotalParsing($vendorFileId) {
		$totalParsedQuery = '
			SELECT id as count FROM {{vendor_normalized}} vn 
			WHERE vendor_fileupload_id = '. (int) $vendorFileId .'
		';

		$totalParsedCommand = Yii::app()->db->createCommand($totalParsedQuery);
		$totalParsedData = $totalParsedCommand->queryAll();

		return count($totalParsedData);
	}*/

	public static function countTotalParsed($actionId) {
		$totalParsedQuery = '
			SELECT count(id) as count FROM {{cron_product_action_product_list}} vn 
			WHERE action_id = '. (int) $actionId .'
		';

		$totalParsedCommand = Yii::app()->db->createCommand($totalParsedQuery);
		$totalParsedData = $totalParsedCommand->queryAll();
		return $totalParsedData[0]['count'];
	}

	public static function countStatusDone($actionId) {
		$totalParsedQuery = '
			SELECT count(id) as count FROM {{cron_product_action_product_list}} vn 
			WHERE action_id = '. (int) $actionId .' and status = '. CronProductActionProductList::STATUS_DONE .'
		';

		$totalParsedCommand = Yii::app()->db->createCommand($totalParsedQuery);
		$totalParsedData = $totalParsedCommand->queryAll();
		return $totalParsedData[0]['count'];
	}

	/*public static function countStatusForReview($vendorFileId) {
		$forReviewQuery = '
			SELECT id as count FROM {{vendor_normalized}} vn 
			WHERE vendor_fileupload_id = '. $vendorFileId .' 
			AND status = '. (int) self::STATUS_FOR_REVIEW .'
		';

		$forReviewCommand = Yii::app()->db->createCommand($forReviewQuery);
		$forReviewData = $forReviewCommand->queryAll();

		return count($forReviewData);
	}

	public static function countStatusPushing($vendorFileId) {
		$pushingQuery = '
			SELECT id as count FROM {{vendor_normalized}} vn 
			WHERE vendor_fileupload_id = '. $vendorFileId .' 
			AND status = '. (int) self::STATUS_PUSHING .'
		';

		$pushingCommand = Yii::app()->db->createCommand($pushingQuery);
		$pushingData = $pushingCommand->queryAll();

		return count($pushingData);
	}

	public static function countStatusPushed($vendorFileId) {
		$pushedQuery = '
			SELECT id as count FROM {{vendor_normalized}} vn 
			WHERE vendor_fileupload_id = '. $vendorFileId .' 
			AND status = '. (int) self::STATUS_PUSHED .'
		';

		$pushedCommand = Yii::app()->db->createCommand($pushedQuery);
		$pushedData = $pushedCommand->queryAll();

		return count($pushedData);
	}

	public static function countStatusError($vendorFileId) {
		$errorQuery = '
			SELECT id as count FROM {{vendor_normalized}} vn 
			WHERE vendor_fileupload_id = '. $vendorFileId .' 
			AND status IN ('. (int) self::STATUS_ERROR_PUSHING .', '. (int) self::STATUS_ERROR_VALIDATION .')
		';

		$errorCommand = Yii::app()->db->createCommand($errorQuery);
		$errorData = $errorCommand->queryAll();

		return count($errorData);
	}

	public static function countStatusDeleted($vendorFileId) {
		$deletedQuery = '
			SELECT id as count FROM {{vendor_normalized}} vn 
			WHERE vendor_fileupload_id = '. $vendorFileId .' 
			AND status = '. (int) self::STATUS_DELETED .'
		';

		$deletedCommand = Yii::app()->db->createCommand($deletedQuery);
		$deletedData = $deletedCommand->queryAll();

		return count($deletedData);
	}

	public static function getNormalizedFiles($vendorFileId) {
		$vendorFilesQuery = '
			SELECT vf.*, f.date_created, v.name as vendor_name, f.original_filename FROM {{vendor_normalized}} vn 
			INNER JOIN {{vendor_file}} AS vf ON vf.id = vn.vendor_fileupload_id
			INNER JOIN {{fileupload}} AS f ON f.id = vf.fileupload_id
			INNER JOIN {{vendor}} AS v ON v.id = vf.vendor_id
			WHERE vendor_fileupload_id = '. $vendorFileId .' 
			AND vn.status IN (
				'. (int) self::STATUS_FOR_REVIEW .', 
				'. (int) self::STATUS_PUSHING .', 
				'. (int) self::STATUS_PUSHED .')
			GROUP BY vf.id
		';

		$vendorFilesCommand = Yii::app()->db->createCommand($vendorFilesQuery);
		$vendorFilesData = $vendorFilesCommand->queryAll();

		return $vendorFilesData;
	}

	public function getVendorName() {
		return $this->vendorFile->vendor->name;
	}

	public static function productCheckStatus($data) {
		$isNew = ProductInfo::model()->findAll([
			'alias' => 'pi',
			'join' => 'INNER JOIN {{product}} AS p ON p.id = pi.product_id',
			'condition' => 'pi.mpn = :mpn AND p.status <> :status',
			'params' => [':mpn' => trim($data['mpn']), ':status' => Product::STATUS_DELETED]
		]);

		if (!$isNew) {
			return VendorNormalized::PRODUCT_STATUS_NEW;
		}

		$isRemain = ProductInfo::model()->findAll([
			'alias' => 'pi',
			'join' => 'INNER JOIN {{product}} AS p ON p.id = pi.product_id',
			'condition' => '
				pi.sku = :sku AND
				pi.mpn = :mpn AND
				pi.msrp = :msrp AND
				pi.cost = :cost AND
				pi.description = :description AND
				pi.ean = :ean AND
				pi.width = :width AND
				pi.length = :length AND
				pi.height = :height AND
				pi.weight = :weight AND
				p.status <> :status
			',
			'params' => [
				':sku' => trim($data['sku']),
				':mpn' => trim($data['mpn']),
				':msrp' => (float) $data['msrp'],
				':cost' => (float) $data['cost'],
				':description' => trim($data['description']),
				':ean' => trim($data['ean']),
				':width' => trim($data['width']),
				':length' => trim($data['length']),
				':height' => trim($data['height']),
				':weight' => trim($data['weight']),
				':status' => Product::STATUS_DELETED
			]  
		]);

		if ($isRemain) {
			return VendorNormalized::PRODUCT_STATUS_REMAIN;
		} else {
			return VendorNormalized::PRODUCT_STATUS_UPDATED;
		}
	}

	public static function getProductStatusList($withColor = false) {
		if ($withColor) {
			return array(
				self::PRODUCT_STATUS_NOT_CHECKED => '<span class="label label-danger">Re-Check</span>',
				self::PRODUCT_STATUS_NEW => '<span class="label label-success">New</span>',
				self::PRODUCT_STATUS_UPDATED => '<span class="label label-info">Updated</span>',
				self::PRODUCT_STATUS_REMAIN => '<span class="label label-default">Exist</span>',
				self::PRODUCT_STATUS_EOL => '<span class="label label-warning">EOL</span>'
			);
		} else {
			return array(
				self::PRODUCT_STATUS_NOT_CHECKED => 'Rechecked',
				self::PRODUCT_STATUS_NEW => 'New',
				self::PRODUCT_STATUS_UPDATED => 'Updated',
				self::PRODUCT_STATUS_REMAIN => 'Exist',
				self::PRODUCT_STATUS_EOL => 'EOL',
			);
		}
	}

	public static function getProductStatusLabel($index) {
		return self::getProductStatusList()[$index];
	}

	public static function getProductStatusLabelWithColor($index) {
		return self::getProductStatusList(true)[$index];
	}

	public static function countProductCheckStatuses() {
		$query = '
			SELECT vn.product_status, count(*) as count FROM {{vendor_normalized}} AS vn
			INNER JOIN {{vendor_file}} AS vf ON vf.id = vn.vendor_fileupload_id
			WHERE vf.status IN ('. VendorFile::STATUS_FOR_REVIEW .')
			AND vn.status in (
				'. VendorNormalized::STATUS_FOR_REVIEW .',
				'. VendorNormalized::STATUS_PUSHING .',
				'. VendorNormalized::STATUS_PUSHED .',
				'. VendorNormalized::STATUS_ERROR .',
				'. VendorNormalized::STATUS_ERROR_PUSHING .',
				'. VendorNormalized::STATUS_ERROR_VALIDATION .')
			GROUP BY vn.product_status
		';

		$command = Yii::app()->db->createCommand($query);
		$results = $command->queryAll();
		
		$formatedData = [
			self::PRODUCT_STATUS_NEW => 0,
			self::PRODUCT_STATUS_UPDATED => 0,
			self::PRODUCT_STATUS_REMAIN => 0,
			self::PRODUCT_STATUS_EOL => 0
		];

		foreach ($results as $result) {
			$formatedData[(int) $result['product_status']] = $result['count'];
		}

		return $formatedData;
	}

	public static function countStatuses() {
		$query = '
			SELECT vn.status, count(*) as count FROM {{vendor_normalized}} AS vn
			INNER JOIN {{vendor_file}} AS vf ON vf.id = vn.vendor_fileupload_id
			WHERE vf.status IN ('. VendorFile::STATUS_FOR_REVIEW .')
			AND vn.status in (
				'. VendorNormalized::STATUS_FOR_REVIEW .',
				'. VendorNormalized::STATUS_PUSHING .',
				'. VendorNormalized::STATUS_PUSHED .',
				'. VendorNormalized::STATUS_ERROR .',
				'. VendorNormalized::STATUS_ERROR_PUSHING .',
				'. VendorNormalized::STATUS_DELETED .',
				'. VendorNormalized::STATUS_ERROR_VALIDATION .')
			GROUP BY vn.status
		';

		$command = Yii::app()->db->createCommand($query);
		$results = $command->queryAll();
		
		$formatedData = [
			self::STATUS_FOR_REVIEW => 0,
			self::STATUS_PUSHING => 0,
			self::STATUS_PUSHED => 0,
			self::STATUS_DELETED => 0,
			self::STATUS_ERROR => 0
		];

		foreach ($results as $result) {
			if ($result['status'] == self::STATUS_ERROR_PUSHING) 
				$formatedData[self::STATUS_ERROR] += $result['count'];
			else if ($result['status'] == self::STATUS_ERROR_VALIDATION) 
				$formatedData[self::STATUS_ERROR] += $result['count'];
			else
				$formatedData[(int) $result['status']] = $result['count'];

		}

		return $formatedData;
	}

	public static function countParsedData() {
		$query = '
			SELECT * FROM {{vendor_normalized}} AS vn
			INNER JOIN {{vendor_file}} AS vf ON vf.id = vn.vendor_fileupload_id
			WHERE vf.status IN ('. VendorFile::STATUS_FOR_REVIEW .') 

			AND vn.status in (
				'. VendorNormalized::STATUS_FOR_REVIEW .',
				'. VendorNormalized::STATUS_PUSHING .',
				'. VendorNormalized::STATUS_PUSHED .',
				'. VendorNormalized::STATUS_ERROR .',
				'. VendorNormalized::STATUS_ERROR_PUSHING .',
				'. VendorNormalized::STATUS_ERROR_VALIDATION .')
		';

		$command = Yii::app()->db->createCommand($query);
		$results = $command->queryAll();
		
		return count($results);
	}*/
}
