<?php
namespace SabaiApps\Directories\Component\Voting\CSVImporter;

use SabaiApps\Directories\Component\CSV\Importer\AbstractImporter;
use SabaiApps\Directories\Component\Entity\Model\Bundle;
use SabaiApps\Directories\Component\Entity\Model\Field;

class VotingCSVImporter extends AbstractImporter {

	public function csvImporterSupports( Bundle $bundle, Field $field ) {
		if ( ! $voting = (array) $this->_application->Entity_BundleTypeInfo( $bundle, 'voting_enable' ) ) {
			return false;
		}

		return in_array( substr( $field->getFieldName(), strlen( 'voting_' ) ), $voting );
	}

	public function csvImporterDoImport( Field $field, array $settings, $column, $value, &$formStorage, array &$logs ) {
		if ( ( ! $value = json_decode( $value ) )
			|| ! is_array( $value )
		) {
			return;
		}

		switch ( $this->_name ) {
			case 'voting_vote':
				$ret = array();
				if ( ! isset( $value[0] ) ) {
					$value = array( $value );
				}
				// Need to convert each to array since json_decode will return object(s)
				foreach ( $value as $_value ) {
					$_value = (array) $_value;
					foreach ( array( 'sum', 'count' ) as $name ) {
						if ( ! empty( $_value[ $name . '_init' ] ) ) {
							$_value[ $name ] = 0;
						}
					}
					$ret[] = $_value;
				}
				return $ret;
		}
	}
}
