import React from "react";
import Link from "next/link";
import { SpinnerCircular } from "spinners-react";
import moment from "moment";
import fileDownload from 'js-file-download';

import { getCertificates, isPluginCryptoProInstalled, generateSignature } from "../../../utils/digital_signature";
import { downloadQuestionnaire, uploadSignedFile } from "../../../actions";
export default class DigitalSignaturesList extends React.Component
{
	constructor(props)
	{
		super(props);

		this.state = {
			loading: true, 
			certificates_error: null, 
			certificate_selected: undefined, 
			signing: false, 
		};
	}

	componentDidMount()
	{
		const script = document.createElement("script");
		script.src = `${ process.env.NEXT_PUBLIC_SELF_API_HOST }/assets/js/cadesplugin_api.js`;
		script.async = true;
		document.body.appendChild(script);

		setTimeout(() => 
		{
			isPluginCryptoProInstalled()
			.then(setTimeout(() => 
				{
					getCertificates()
					.then(certificates => 
					{
						const certificates_list = [];
						for(let i in certificates)
						{
							const certificate = certificates[i];

							if(certificate?.info?.subjectFields['ИНН ЮЛ'] !== null || certificate?.info?.subjectFields['ИНН'] !== null)
							{
								if(certificate?.info?.subjectFields['ОГРНИП'] !== null || certificate?.info?.subjectFields['ОГРН'] !== null)
								{									
									let today = moment();
									if(today < moment(certificate.info.validToDate))
									{
										certificate.info.validToDate = moment(certificate.info.validToDate).format('DD.MM.YYYY');
										certificates_list.push(certificate);
									}
								}
							}
						}
						
						this.setState({ certificates: certificates_list, certificates_error: certificates_list.length > 0 ? null : "ISSUED", loading: false });
					})
					.catch((error_get_certificates) => 
					{
						console.error("error_get_certificates");
						console.error(error_get_certificates);
						console.log("certificates", 'OTHER');
						this.setState({ certificates: [], certificates_error: "OTHER", loading: false });
					})
				}, 500)
			)
			.catch((error_plugin_installed) => 
			{
				console.error("error_plugin_installed");
				console.error(error_plugin_installed);
				console.log("certificates", 'NOT_INSTALLED');
				this.setState({ certificates: [], certificates_error: "NOT_INSTALLED", loading: false })
			});
		}, 1000);
	}

	componentDidUpdate(prevProps, prevState)
	{
	}

	_sign = () => 
	{
		this.setState({ signing: true }, () => 
		{
			const { company, main, onSignDigital } = this.props;
			const filename = `${ main.inn }_questionnaire_${ moment().format("DDMMYYYY_HHmmss") }.pdf`;
	
			downloadQuestionnaire({ filename, download: false })
			.then(({ file }) => 
			{
				let file_to_sign = new File([ file ], filename);
		
				const now = moment().format("DDMMYYYY_HHmmss");
				generateSignature(file_to_sign, this.state.certificate_selected.certificate)
				.then(signature => 
				{
					console.log("signature");
					console.log(signature);
	
					uploadSignedFile(signature, company.questionnaire_id, true)
					.then(() => 
					{
						onSignDigital();
					})
					.catch(() => 
					{
						this.setState({ signing: false });
					});
				})
				.catch(() => 
				{
					this.setState({ signing: false });
				})
			  })
			.catch((e) => 
			{
				console.error("exception on sign");
				console.error(e);
	
				let errorsText = {
					'The action was cancelled by the user. (0x8010006E)': 'Подписание было отменено',
					'Key does not exist. (0x8009000D)': 'Сертификата не существует',
					'Keyset does not exist (0x80090016)': 'Набор ключей не существует',
					'File upload error': 'Ошибка загрузки файла',
					'Invalid algorithm specified. (0x80090008)': 'На вашем компьютере не установлена программа «КриптоПро CSP»',
					'The card cannot be accessed because the wrong PIN was presented. (0x8010006B)': 'Указанный пароль неверный'
				}
	
				if(e !== undefined)
				{
					let errorText = errorsText[e.message] || 'Ошибка подписания файла';
					alert(errorText);
				}
			});
		});
	}

	render()
	{
		const { certificates, certificates_error, certificate_selected, loading, signing } = this.state;
		console.log(certificates);

		if(loading)
		{ 
			return (
				<div style={{ minHeight: 200, display: "flex", justifyContent: "center", alignItems: "center", }}>
					<SpinnerCircular size={ 90 } thickness={ 51 } speed={ 100 } color="rgba(28, 1, 169, 1)" secondaryColor="rgba(236, 239, 244, 1)" />
				</div>
			); 
		}
		else
		{
			if(certificates_error === null)
			{
				return (
					<React.Fragment>
					<div className="feed">
						<p>Выберите подписанта</p>
						<div className="feed_list">

							{ certificates.map((certificate, index) => (
								<div className="form_field checkbox" key={ index }>
									<input type="radio" 
										hidden="" 
										id={ `certificate_${ certificate.index }` } 
										name={ `certificate_${ certificate.index }` } 
										checked={ certificate_selected !== undefined && certificate_selected.index === certificate.index ? true : false } 
										onChange={ () => { this.setState({ certificate_selected: certificate }) } }
									/>
									<label htmlFor={ `certificate_${ certificate.index }` }>
										<div className="feed_item user">
											<img src="/assets/images/icons/avatar.svg" alt="" />
											<div>
												<p className="item_title">{ certificate?.info?.subjectName.replace(/"/g, '') }</p>
												<p className="item_desc">
													{ certificate.info.subjectFields['SN'] ? (<span>{ certificate.info.subjectFields['SN'] } { certificate.info.subjectFields['G'] }</span>) : null }
												</p>
												<p className="item_desc">
													<span>ИНН { certificate?.info?.subjectFields['ИНН ЮЛ'] !== null ? certificate?.info?.subjectFields['ИНН ЮЛ'] : certificate.info.subjectFields['ИНН'] }</span>
												</p>
												<p className="item_desc">
													{ certificate?.info?.subjectFields['ОГРНИП'] && (<span>ОГРНИП { certificate.info.subjectFields['ОГРНИП'] }</span>) } 
													{ certificate?.info?.subjectFields['ОГРН'] && (<span>ОГРН { certificate.info.subjectFields['ОГРН'] }</span>) } 
												</p>
												<p className="item_desc">
													<span>Подпись действительна до { certificate?.info?.validToDate }</span> 
												</p>
											</div>
										</div>
									</label>
								</div>
							)) }
	
						</div>
					</div>
					<div className="action" style={{marginBottom: "20px"}}>
						<div></div>
						<button 
							type="submit" 
							className="button button-blue" 
							disabled={ certificate_selected !== undefined ? false : true } 
							onClick={ this._sign } 
							style={{ minWidth: "250px" }} 
						>
							{ signing ? (
								<SpinnerCircular size={24} thickness={100} speed={100} color="rgba(255, 255, 255, 1)" secondaryColor="rgba(255, 255, 255, 0.5)" style={{ marginTop: "4px" }}/>
							) : "Подписать выбранной подписью" }
						</button>
					</div>
				</React.Fragment>
				)
			}
			else
			{
				return (
					<div className="questionnaire message error">
						<svg width="44" height="45" viewBox="0 0 44 45" fill="none" xmlns="http://www.w3.org/2000/svg">
							<path d="M40.5425 31.1863L25.7969 8.08116C24.9653 6.77804 23.5459 6 22 6C20.4539 6 19.0345 6.77804 18.2032 8.08116L3.45741 31.1862C2.57234 32.5732 2.51363 34.3313 3.30467 35.7746C4.09572 37.2173 5.60918 38.1137 7.25444 38.1137H36.7456C38.3909 38.1137 39.9044 37.2175 40.6956 35.7742C41.4863 34.3313 41.4276 32.5733 40.5425 31.1863ZM22 34.2245C20.644 34.2245 19.5448 33.1252 19.5448 31.7694C19.5448 30.4133 20.6441 29.3141 22 29.3141C23.356 29.3141 24.4551 30.4133 24.4551 31.7694C24.4551 33.1252 23.3559 34.2245 22 34.2245ZM25.403 17.1635L24.1937 25.3052C24.0157 26.5037 22.8999 27.3309 21.7016 27.1529C20.7334 27.0091 20.0075 26.25 19.8582 25.333L18.5451 17.2074C18.2394 15.3155 19.5251 13.534 21.417 13.2283C23.3089 12.9226 25.0904 14.2083 25.3962 16.1002C25.4536 16.4565 25.4517 16.8243 25.403 17.1635Z" fill="white"/>
						</svg>
						{ certificates_error === "NOT_INSTALLED" && (
							<p><b>Ошибка</b>
								Плагин КриптоПРО не установлен, <Link href="https://cryptopro.ru/products/cades/plugin"><a target="_blank" rel="noopener noreferrer" style={{ color: "white", textDecoration: "underline" }}>посмотрите инструкцию</a></Link> как установить плагин КриптоПРО.
							</p>
						) }
						{ certificates_error === "OTHER" && (
							<p><b>Ошибка</b>
								Плагин КриптоПРО не активирован, пожалуйста, обновите страницу и подтвердите разрешение для сайта на доступ к списку сертификатов.
							</p>
						) }
						{ certificates_error === "ISSUED" && (
							<p><b>Ошибка</b>
								Отсутствуют действующие сертификаты.
							</p>
						) }
						{ certificates_error === "MISMATCH" && (
							<p><b>Ошибка</b>
								Подписант не соответствует указанному подписанту в анкете.
							</p>
						) }
					</div>
				)
			}
		}
	}
}