import React from 'react';
import fetch from 'unfetch';
import { connect } from 'react-redux'; // https://react-redux.js.org/introduction/quick-start
import ImportDesignsButton from './import-designs-button.jsx';
import {
	setImportStatus,
	setImportProgress,
	setImportTotal,
} from './actions/ui-actions';

const { Fragment } = wp.element;
const { cloneDeep, isEmpty } = window.lodash;

class DesignsImporter extends React.Component {
	/**
	 * Import designs from remote server to the local website.
	 *
	 * @function importDesigns
	 * @param  {string} setId Design set unique id.
	 * @return {void}
	 */
	importDesigns = ( setId = 'basic' ) => {
		this.props.updateImportStatus( true );

		fetch( window.ajaxurl, {
			method: 'POST',
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
			},
			body:
				'action=dsgn_design_import&_wpnonce=' +
				window.dsgnjs.nonce +
				'&design_set=' +
				setId,
			credentials: 'same-origin',
		} ).then( response => {
			if ( response.ok ) {
				response.json().then( responseDecoded => {
					this.importThumbnails( JSON.parse( responseDecoded.data ) );
				} );
			} else {
				const error = new Error( response.statusText );
				error.response = response;
				// eslint-disable-next-line no-console
				console.warn( error );
			}
		} );
	};

	importThumbnails = importData => {
		if ( isEmpty( importData ) ) {
			// NOTHING TO IMPORT!
			return;
		}

		const designSetId = Object.keys( importData )[ 0 ];
		const allDesigns = importData[ designSetId ].designs;
		const designsToImport = [];

		// No designs left in the current [0] deisgn set.
		if ( ! allDesigns.length ) {
			// Remove empty set from the import data object.
			delete importData[ Object.keys( importData )[ 0 ] ];
			// Check if we have any other data left after previous deletion?
			if ( ! isEmpty( importData ) ) {
				// There are other sets left. Restart process for them.
				this.importThumbnails( importData );
			}
			this.props.updateImportStatus( false );
			this.props.updateImportTotal( 0 );
			this.props.updateImportProgress( 0 );

			this.props.getLibrary();
			// All done. Go home pal!
			return;
		}

		// Add next 10 design into designsToImport array.
		while ( designsToImport.length < 10 ) {
			if ( ! isEmpty( allDesigns[ 0 ] ) ) {
				designsToImport.push( allDesigns[ 0 ] );
				allDesigns.splice( 0, 1 );
			} else {
				break;
			}
		}

		const dataToImport = cloneDeep( importData );
		dataToImport[ designSetId ].designs = designsToImport;

		// Dispatch some actions
		if ( allDesigns.length > this.props.total ) {
			this.props.updateImportTotal( allDesigns.length );
		}
		this.props.updateImportProgress( designsToImport.length );

		// IMPORT DESIGNS FROM designsToImport:
		fetch( window.ajaxurl, {
			method: 'POST',
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
			},
			body:
				'action=dsgn_thumbnails_import&_wpnonce=' +
				window.dsgnjs.nonce +
				'&data_to_import=' +
				JSON.stringify( dataToImport ),
			credentials: 'same-origin',
		} )
			.then( response => {
				if ( response.ok ) {
					response.text().then( text => {
						if ( text !== '1' ) {
							this.setState( { errorMessage: text } );
							this.props.updateImportStatus( false );
						} else {
							// There are more designs to import so do another round.
							this.importThumbnails( importData );
						}
					} );
				} else {
					const error = new Error( response.statusText );
					error.response = response;
					// eslint-disable-next-line no-console
					console.warn( error );
				}
			} )
			.then( () => {
				return 'complete';
			} );
	};

	render() {
		return (
			<Fragment>
				<ImportDesignsButton
					userStatus={ this.props.userStatus }
					importDesigns={ this.importDesigns }
					progress={ this.props.progress }
					importing={ this.props.importing }
					importedSets={ this.props.importedSets }
				/>
			</Fragment>
		);
	}
}

// https://react-redux.js.org/introduction/basic-tutorial#connecting-the-components

export default connect(
	// mapStateToProps
	state => ( {
		userStatus: state.user.status,
		progress: state.ui.importProgress.imported,
		importing: state.ui.importProgress.importing,
		total: state.ui.importProgress.total,
		importedSets: state.designs.importedSets,
	} ),
	//mapDispatchToProps
	dispatch => ( {
		updateImportStatus: newStatus => {
			dispatch( setImportStatus( newStatus ) );
		},

		updateImportTotal: designsTotal => {
			dispatch( setImportTotal( designsTotal ) );
		},

		updateImportProgress: currentStep => {
			dispatch( setImportProgress( currentStep ) );
		},
	} )
)( DesignsImporter );
