/**
 * BLOCK: Comment Averages
 */

const { __ } = wp.i18n;
const { registerBlockType } = wp.blocks;
const el = wp.element.createElement;

const { 
	apiFetch 
} = wp;

const {
    InspectorControls,
    MediaUploadCheck,
    PanelColorSettings,
    MediaUpload,
} = wp.editor;

const {
	SelectControl,
	TextControl,
	ServerSideRender,
    PanelBody,
} = wp.components;
const { 
	withSelect,
	registerStore
} = wp.data;

const iconEl = el('svg', { width: 20, height: 20 },
  el('path', { d: "M19,0 C19.5522847,-1.01453063e-16 20,0.44771525 20,1 L20,19 C20,19.5522847 19.5522847,20 19,20 L1,20 C0.44771525,20 6.76353751e-17,19.5522847 0,19 L0,1 C-6.76353751e-17,0.44771525 0.44771525,1.01453063e-16 1,0 L19,0 Z M18,2 L2,2 L2,18 L18,18 L18,2 Z M10,5 L11.4694631,7.97745751 L14.7552826,8.45491503 L12.3776413,10.7725425 L12.9389263,14.045085 L10,12.5 L7.06107374,14.045085 L7.62235871,10.7725425 L5.24471742,8.45491503 L8.53053687,7.97745751 L10,5 Z" } )
);


const actions = {
	setPosts( posts ) {
		return {
			type: 'SET_POSTS',
			posts,
		};
	},
	getPosts( path ) {
		return {
			type: 'GET_POSTS',
			path,
		};
	},
};

const store = registerStore( 'codetipi-lets-review', {
	reducer( state = { posts: {} }, action ) {

		switch ( action.type ) {
			case 'SET_POSTS':
				return {
					...state,
					posts: action.posts,
				};
		}

		return state;
	},

	actions,

	selectors: {
		getPosts( state ) {
			const { posts } = state;
			return posts;
		},
	},

	controls: {
		GET_POSTS( action ) {
			return apiFetch( { path: action.path } );
		},
	},

	resolvers: {
		* getPosts( state ) {
			const posts = yield actions.getPosts( '/codetipi-lets-review/v3/posts/' );
			return actions.setPosts( posts );
		},
	},
} );

registerBlockType( 'lets-review/block-comment-averages', {
	title: __( 'Comment Reviews Averages', 'lets-review' ),
	description: __( 'Show the average scores left by visitors via the comment reviews in any post.', 'lets-review' ),
	icon: iconEl,
	category: 'lets-review-blocks',
	keywords: [
		__( 'comments', 'lets-review' ),
		__( 'review', 'lets-review' ),
		__( 'visitors', 'lets-review' ),
		'lets review',
		"Let's Review",
		'lets-review',
	],
	attributes: {
        pid: {
            type: 'string',
        },
        title: {
            type: 'string',
            default: __( 'Average User Ratings', 'lets-review' ),
        },
        isguten: {
            type: 'boolean',
            default: true,
        },
        bgID: {
			type: 'integer',
		},
		bgThumb: {
			type: 'string',
		},
		scoreType: {
			type: 'string',
			default: '1',
		},
		skinBG: {
			type: 'string',
			default: '#111',
		},
		skinText: {
			type: 'string',
			default: '#fff',
		},
		skinTitles: {
			type: 'string',
			default: '#ead125',
		},
		accent: {
			type: 'string',
			default: '#f8d92f',
		},
        design: {
			type: 'string',
			default: '1',
		},
		skin: {
			type: 'string',
			default: '1',
		},
    },
	edit: withSelect( function( select ) {
        return {
        	posts: select('codetipi-lets-review').getPosts(),
        };
    } )( function( props ) {

		const { setAttributes, attributes } = props;
        let critsOn = true,
			bgImgOn = false,
			barsAniOn = true,
			skin = parseInt( attributes.skin ),
			design = parseInt( attributes.design );

		if ( design === 3 || design === 4 ) {
			bgImgOn = true;
			barsAniOn = false;
		}

		let bgImagePlaceholder = __('Change Background Image');
		if ( design === 6 ) {
			bgImagePlaceholder = __('Change Main Image');
			skin = 2;
		}
        if ( ! props.posts ) {
            return __( 'Loading...', 'lets-review' );
        }

        if ( props.posts.length === 0 ) {
            return __( 'No posts', 'lets-review' );
        }
 		if ( typeof attributes.pid === 'undefined' && typeof props.posts[0] !== 'undefined' ) {
 			setAttributes( { pid: props.posts[0].value } );
 		}

 		function onImageSelect( attr, imageObject) {
			var thumb;
			if ( typeof imageObject.sizes.medium !== 'undefined' && imageObject.sizes.medium.width > 0 ) {
				thumb = imageObject.sizes.medium.url;
			} else if ( typeof imageObject.sizes.full !== 'undefined' && imageObject.sizes.full.width > 0 ) {
				thumb = imageObject.sizes.full.url
			} else if ( typeof imageObject.sizes.thumbnail !== 'undefined' && imageObject.sizes.thumbnail.width > 0 ) {
				thumb = imageObject.sizes.thumbnail.url
			}
			if ( attr === 'bg' ) {
				thumb = imageObject.sizes.full.url;
			}
			setAttributes({
				[ attr + 'ID']: imageObject.id,
				[ attr + 'Thumb']: thumb
			})
		}

		var scoreTypeOptions = [
				{ label: __( 'Percentage' ), value: '1' },
				{ label: __( 'Points' ), value: '2' },
			];

		return ([
			<InspectorControls>
				<PanelBody title={ __( 'Block Options', 'lets-review' ) }>
				    <SelectControl 
			        value={ attributes.pid } 
			        onChange={ ( value ) => setAttributes( { pid: value } ) }
			        label={ __( 'Select Post', 'lets-review' ) } 
			        options={ props.posts } />
			 		<TextControl
			        	label={ __( 'Title', 'lets-review' ) }
						onChange={ ( value ) => setAttributes( { title: value } ) }
						value={attributes.title}
					/>
					<SelectControl
							label={__('Design')}
							value={ attributes.design }
							options={ [
								{ label: __( 'Minimalist' ), value: '1' },
								{ label: __( 'Minimalist B' ), value: '6' },
								{ label: __( 'Bold' ), value: '2' },
							] }
							onChange={ function( value ) {
								if ( 6 === parseInt(value) && parseInt( attributes.scoreType ) > 2 ) {
									setAttributes( { design: value, scoreType: '1'  } )
								} else {
									setAttributes( { design: value } )
								}
							} }
						/>
						<SelectControl
						label={__('Score Type')}
						value={ attributes.scoreType }
						options={ scoreTypeOptions }
						onChange={ ( value ) => setAttributes( { scoreType: value } ) }
					/>
						{ bgImgOn === true ? <div class="components-base-control inspector__upload"><MediaUploadCheck><MediaUpload
							onSelect={onImageSelect.bind( this, 'bg' )}
							type="image"
							value={attributes.bgID}
							render={({ open }) => (
								<button class="components-button is-button is-default is-large" onClick={open}>{bgImagePlaceholder}</button>
							)}
						/></MediaUploadCheck></div> : <SelectControl
						label="Skin"
						value={ attributes.skin }
						options={ [
							{ label: __( 'Light' ), value: '1' },
							{ label: __( 'Dark' ), value: '2' },
							{ label: __( 'Custom' ), value: '3' },
						] }
						onChange={ ( value ) => setAttributes( { skin: value } ) }
					/>}
				</PanelBody>
				<PanelColorSettings
					title={ __( 'Color Settings' ) }
					colorSettings={ [
						{
							value: attributes.accent,
                			onChange: ( value ) => setAttributes( { accent: value } ),
							label: __( 'Accent Color' ),
						},
					] }
				>
				</PanelColorSettings>
				{ parseInt( attributes.skin ) === 3 && design !== 6 ? (
					<PanelColorSettings
						title={ __( 'Color Settings' ) }
						colorSettings={ [
							{
								value: attributes.skinBG,
                    			onChange: ( value ) => setAttributes( { skinBG: value } ),
								label: __( 'Background Color' ),
							},
							{
								value: attributes.skinTitles,
								onChange: ( value ) => setAttributes( { skinTitles: value } ),
								label: __( 'Titles Color' ),
							},
							{
								value: attributes.skinText,
								onChange: ( value ) => setAttributes( { skinText: value } ),
								label: __( 'Body Color' ),
							},
						] }
					>
					</PanelColorSettings>
				) : ''}
			</InspectorControls>,
			el(ServerSideRender, {
                block: "lets-review/block-comment-averages",
                attributes:  attributes
            })
		]);
	}),

	save: function( props ) {
		return null
	},
} );
