<?php

class Netbase_Theme_Updater {

	private $repository;

	private $authorize_token;

	private $github_response;

	private $theme_directory;

	private $theme_slug;

	private $theme_url;

	public function __construct( $theme_directory, $theme_slug, $theme_url ) {

		$this->theme_directory 	= $theme_directory;
		$this->theme_slug 		= $theme_slug;
        $this->theme_url 		= $theme_url;

		return $this;
	}

	public function set_repository( $repository ) {
		$this->repository = $repository;
	}

	public function set_token( $token ) {
		$this->authorize_token = $token;
	}

	private function get_repository_info() {
			
		$request_uri = sprintf('https://gitlab.com/api/v4/projects/%s/repository/tags?private_token=%s', $this->repository, $this->authorize_token);

		$response = json_decode( wp_remote_retrieve_body( wp_remote_get( $request_uri ) ), true );

		if( is_array( $response ) ) {
			$response = current( $response );
		}

		$this->github_response = $response;
	}

	public function initialize() {
		add_filter( 'pre_set_site_transient_update_themes', array( $this, 'modify_theme_transient' ), 10, 1 );
		add_filter( 'upgrader_source_selection', array( $this, 'rename_theme_package_zip' ), 1, 4);
	}

	public function modify_theme_transient( $transient ) {

        $checked = isset($transient->checked) ? $transient->checked : array();

		if( $checked ) {

			$this->get_repository_info();

			$out_of_date = version_compare( $this->github_response["name"], $checked[$this->theme_slug], 'gt' );

			if( $out_of_date ) {

				$new_files = sprintf('https://gitlab.com/api/v4/projects/%s/repository/archive.zip?sha=%s&private_token=%s', $this->repository, $this->github_response["name"], $this->authorize_token);

				$upgrade_theme_data = array(
					'url' 			=> $this->theme_url,
					'theme' 		=> $this->theme_slug,
					'package' 		=> $new_files,
					'new_version' 	=> $this->github_response["name"]
				);

				$transient->response[$this->theme_slug] = $upgrade_theme_data;
			}
		}

		return $transient;
	}

	public function rename_theme_package_zip( $source, $remote_source, $thiz, $extra_params )
	{
		if(isset($extra_params['theme'])) {
			$theme_source = str_replace($remote_source, '', $source);
			if(  strpos( $theme_source, $this->theme_slug) === false )
				return $source;
				
			$path_parts = pathinfo( $source );
			
			$newsource = trailingslashit( $path_parts['dirname'] ) . trailingslashit( $this->theme_slug );
			rename( $source, $newsource );
			return $newsource;
		}
		return $source;
		
	}
}