<?php

namespace WPML\ST\BatchAction;

use WPML\Ajax\IHandler;
use WPML\Collect\Support\Collection;
use function WPML\Container\make;
use WPML\FP\Either;
use WPML\FP\Fns;
use WPML\FP\Obj;
use WPML\ST\StringsRepository;

class ChangeLanguageOfStringsInDomain implements IHandler {

	private $sitepress;

	private $stringsRepository;

	private $changeLangDialog;

	public function __construct(
		\SitePress                                 $sitepress,
		StringsRepository                          $stringsRepository,
		\WPML_Change_String_Domain_Language_Dialog $changeLangDialog
	) {
		$this->sitepress         = $sitepress;
		$this->stringsRepository = $stringsRepository;
		$this->changeLangDialog  = $changeLangDialog;
	}

	public function run( Collection $data ) {
		if ( ! current_user_can( 'wpml_manage_string_translation' ) && ! current_user_can( 'manage_translations' ) ) {
			return Either::left( 'not allowed' );
		}

		$domain         = $data->get( 'domain', false );
		$batchSize      = $data->get( 'batchSize', 1 );
		$targetLanguage = $data->get( 'targetLanguage', $this->sitepress->get_default_language() );

		if ( $domain === false ) {
			return Either::left( __( 'Error: please try again', 'wpml-string-translation' ) );
		}

		$langs     = $this->stringsRepository->getLanguagesUsedInDomains( [ $domain ], [ $targetLanguage ] );
		$stringIds = $this->stringsRepository->getStringIdFromDomainsByLangs( [ $domain ], $langs, $batchSize );

		if ( count( $stringIds ) > 0 ) {
			$this->changeLangDialog->changeLanguageOfStrings($stringIds, $targetLanguage);
		}

		return Either::of(
			[
				'completedCount' => count( $stringIds ),
			]
		);
	}
}
