const
 script_name='kino-teatr';
 language='Russian';
 version=11;
 author='BlackStream';
 MinProgramBuild=5500;
 
 PERSON_DIRECTOR = 1;
 PERSON_WRITER   = 2;
 PERSON_ACTOR    = 3;
 PERSON_COMPOSER = 4;
 IMAGE_PHOTO = 6;

var
	DownloadPersonBiography, DownloadPersonAdditionalInfo: boolean;
	MaxPhotosCount: integer;
	persons_count: integer;
	persons: array of string;
	imdb_codes: array of string;
	url_fix: string;
	imdb_code, person_code: string;
	name, code, year, description: string;
	person, BasicURL, biography, trivia, character, birth_date, death_date, birthplace, birth_name, salary, height, original_name, person_site_url: string;
	photo_url: string;
	monthes: array [1..12] of string;
	prefixes: array [1..13] of string;
	person_height: integer;
	is_photos_present: boolean;
	BaseImageURL, photos_url: string;
//==================================================================================================
//  Вспомогательные функции
//==================================================================================================
function GetStr(str: String; s1: String; s2: String): String;
var
  I: Integer;
  J: Integer;
begin
  // Вырезает кусок строки между s1 и s2
	Result := '';
	I := Pos(LowerCase(s1), LowerCase(str));
	if I > 0 then
	begin
		J := MyPos(LowerCase(s2), LowerCase(str), I + Length(s1));
		if J > 0 then
  		Result := Copy(str, I + Length(s1), J - I - Length(s1));
	end;
end;

//==================================================================================================
//  Экспортируемые из скрипта функции
//==================================================================================================

//==================================================================================================
//  01. Формирование URL для поиска актёра на сайте по названию
//==================================================================================================
function GetSearchURLbyName(MovieName: string): string;
var 
	url: string;
	i, j: integer;
begin
	url := 'http://www.kino-teatr.ru/search/?text='+MovieName+'&movie=0&acter=1&submit=submit';
(*	all := DownloadURLWithReferer(url, 'post');
	i := Pos('По вашему запросу ничего не обнаружено...', all);
	if not(i>0) then
	begin
		i := Pos('<a href="/search/', all);
		if i>0 then
		begin
			j := MyPos('/">', all, i+1);
			if j>0 then
				result := 'http://www.kino-teatr.ru'+copy(all, i+9, j-i-9);
		end;
	end
	else
	result := '-1';
*)
	result := url;
end;

//==================================================================================================
//  02. Загрузка html-документа по поисковой ссылке
//==================================================================================================
function DownloadSearchURL(url: string): Integer;
 begin          
  all := DownloadURLWithReferer(url, 'post');
  if (all<>'-1') and (GetResponseCode=200)
   then   Result:=SelectActor
   else   Result:=-1
 end;    

//==================================================================================================
//  03. Парсинг страницы поисков с актёрами
//==================================================================================================
function SelectActor: Integer;
var
	jj, i, j, k, TitlesCount: integer;
	y, x , s, s3, s2, temp: string;
	Actor, Code, small_photo, original_name, description : string; 
begin
	Result:=0;
	i := Pos('<strong>результат поиска</strong>', all);
	if i > 0 then begin
		j := MyPos('</td></tr></table', all, i+1);
		s := copy(all, i, j-i);
		i := Pos('<a href="/kino/', s);
		while i>0 do begin
			j := MyPos('<div class="separator">', s, i+1);
			if j=0 then
				j := Length(s);
			s2 := copy(s, i, j-i);
			actor := GetStr(s2, '<strong>', '</strong>');
			code := GetStr(s2, '<a href="', '"');
			code := ParseString(code, '(\d+)', 1);
			small_photo := GetStr(s2, '<img src="', '"');
			if (small_photo <> '') then begin
				small_photo := ReplaceStr(small_photo, '/pv_', '/', -1);
				small_photo := 'http://www.kino-teatr.ru' + small_photo;
			end;
			temp := GetStr(s2, '<br /><p><a href="/kino/', '</p>');
			original_name := DecodeHTML(RemoveTags(GetStr(temp, '>', '<')));
			//описание
			description := '';
			k := Pos('<p>', s2);
			delete(s2, 1, k-1);
			k := Pos('<p><a href="/kino/', s2);
			if k>0 then begin
				delete(s2, 1, k);
				k := Pos('<p>', s2);
				delete(s2, 1, k-1);
			end;
			description := DecodeHTML(RemoveTags(GetStr(s2, '<p>', '</p>')));
			
			if (Actor<>'') and (Code <> '') then begin
				SetSearchResult2(Actor, Code, '', original_name, description, small_photo);
				Inc(Result);
			end;
			delete(s, 1, j);
			i := Pos('<a href="/kino/', s);
		end;
	end;
end;

//==================================================================================================
//  04. Формирование URL с информацией об актёре по коду актёра в формате сайта 
//==================================================================================================
function GetPersonURL(Code: string; Images_Only: Boolean): string;
 begin
  if Code<>''
   then   Result:='http://kino-teatr.ru/kino/acter/'+Code+'/'
   else   Result:=''
 end;       

//==================================================================================================
//  05. Получение данных по фильму по URL
//==================================================================================================
function GetInfo(URL: string; Images_Only: Boolean): string;
	var
		s, s2, temp, filmo_url: string;
		Movie, Role, Code, Year, day, month: string;
		i, j, jj, k: Integer;
	//set filmography
	procedure GetFilmography(Str: string; mode: byte);
	var
		s, s2: string;
		i, j : integer;
	begin
		s := Str;
		i := Pos('<tr>', s);
		while i>0 do begin
			j := MyPos('</tr>', s, i+1);
			s2 := copy(s, i, j-i);
			Code := '';
			Year := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(GetStr(s2, '<td class="god">', '</td>'))));
			Year := ParseString(Year, '^(\d+)', 1);
			Movie := GetStr(s2, '<td class="name">', '</td>');
			Movie := GetStr(Movie, '<strong>', '</strong>');
			Movie := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(Movie)));
			Code := GetStr(s2, '<a href="/kino/movie/', '"');
			Code := ParseString(Code, '(\d+)', 1);
			Role := '';
			if mode = 3 then begin
				Role := GetStr(s2, '&nbsp;::&nbsp;</b>', '<');
				Role := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(Role)));
				if Role = 'эпизод' then Role := '';
				if Role = 'В титрах не указан' then Role := '';
			end;
			if Movie <> '' then
				SetMovieName(Movie, Role, mode, Code, Year);
			delete(s, 1, i);
			i := Pos('<tr>', s);
		end;
	end;
begin
	filmo_url := '';
	Person_Code:=ParseString(URL, '\/(\d+)\/', 1);
	person_site_url:=GetPersonSiteURL(Person_Code);
	Result:=DownloadURL(URL);
	if (Result='-1') or (GetResponseCode<>200) then
		exit;
	all:=Result;
	if (Pos('/works', url) = 0) and (Pos(Person_code + '/works', all)>0) then begin
		filmo_url := url + 'works';
		AddRequestForHTMLPageContent(filmo_url, False);
	end;
	if (MaxPhotosCount > 0) and (Pos(person_code + '/foto', all)>0) then begin
		photos_url := url + 'foto';
		AddRequestForHTMLPageContent(photos_url, False);
	end;
	person := ParseString(all, '<h2 align="left".*?>(.+)</h2>', 1);
	Person := DecodeHTML(Person);
	
	original_name := GetStr(all, '</h2><p><strong>', '</strong>');
	original_name := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(original_name)));
	//биография
	temp := GetStr(all, '<h3><strong>биография</strong></h3>', '</td></tr></table>');
	i := Pos('</h2>', temp);
	if i>0 then
		delete(temp, 1, i+4);
	i := Pos('последнее обновление информации:', temp);
	if i>0 then
		delete(temp, i, length(temp)-i+1);
	i := Pos('<b>призы и награды</b>', temp);
	if i>0 then begin
		s := copy(temp, i+22, length(temp)-i-21);
		delete(temp, i, length(temp)-i+1);
		description := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(s)));
	end;
	biography := ReplaceStr(temp, '<p></p>', #13#10, -1);
	biography := ClearExtraBlankCharacters(DecodeHTML(RemoveTags(biography)));
	if Pos(original_name, biography)=1 then
		delete(biography, 1, length(original_name));
	biography := ClearExtraBlankCharacters(biography);
	original_name := ReplaceStr(original_name, '  ', ' ', -1);
	//фото
	BaseImageURL := GetStr(all, '<img src="/acter/foto/', '"');
	if BaseImageURL <> '' then
		BaseImageURL := 'http://www.kino-teatr.ru/acter/foto/' + BaseImageURL;
	//даты рождения и смерти
	temp := GetStr(all, '<img src="/acter/foto/', '<form>');
	if temp<>'' then begin
		s := GetStr(temp, '<a href="/day/', '</span>');
		month := ParseString(s, '^(\d+)-', 1);
		day := ParseString(s, '^\d+-(\d+)', 1);
		year := ParseString(s, '<a href="/day/y(\d+)', 1);
		if (month<>'') and (year<>'') and (day<>'') then
		birth_date := format('%s/%s/%s', [month, day, year]);
		s := GetStr(temp, 'a href="/mourn/', '</span>');
		month := ParseString(s, '^(\d+)-', 1);
		day := ParseString(s, '^\d+-(\d+)', 1);
		year := ParseString(s, '<a href="/mourn/y(\d+)', 1);
		if (month<>'') and (year<>'') and (day<>'') then
		death_date := format('%s/%s/%s', [month, day, year]);
	end;
	
	//фильмография
	if (Pos('/works', url) = 0) then
		all := GetHTMLPageContentFromRequest(filmo_url);
	temp := GetStr(all, '<h3><strong>фильмография</strong></h3>', 'последнее обновление информации:');
	i := Pos('<b>роли в кино</b>', temp);
	if i>0 then begin
		j := MyPos('<td colspan="2" class="name">', temp, i+1);
		if j=0 then
			j := Length(temp);
		s := copy(temp, i, j-i);
		GetFilmography(s, 3);
	end;
	i := Pos('<b>Режиссер</b>', temp);
	if i>0 then begin
		j := MyPos('<td colspan="2" class="name">', temp, i+1);
		if j=0 then
			j := Length(temp);
		s := copy(temp, i, j-i);	
		GetFilmography(s, 1);		
	end;
	i := Pos('<b>Сценарист</b>', temp);
	if i>0 then begin
		j := MyPos('<td colspan="2" class="name">', temp, i+1);
		if j=0 then
			j := Length(temp);
		s := copy(temp, i, j-i);	
		GetFilmography(s, 2);		
	end;
	i := Pos('<b>Композитор</b>', temp);
	if i>0 then begin
		j := MyPos('<td colspan="2" class="name">', temp, i+1);
		if j=0 then
			j := Length(temp);
		s := copy(temp, i, j-i);	
		GetFilmography(s, 4);		
	end;
end;

//==================================================================================================
//  06. Загрузка картинок
//==================================================================================================
procedure GetImages;
 var
  temp, s: string;
  c: Integer;
  url: string;
  i, j: integer;
  flPhoto: boolean;
 begin
	c := 0;
	if (BaseImageURL<>'') then begin
		SetImageName('', BaseImageURL, '', IMAGE_PHOTO);
		c := 1;
	end;
	if MaxPhotosCount > c then begin
		temp := GetHTMLPageContentFromRequest(photos_url);
		temp := GetStr(temp, '<h3><strong>фотографии</strong></h3>', '</td></tr></table>');
		i := Pos('<img src="/acter/album/', temp);
		while (i>0) and (MaxPhotosCount > c) do begin
			url := GetStr(temp, '<img src="/acter/album/', '"');
			if url<>'' then begin
				url := ReplaceStr(url, '/pv_', '/', -1);
				url := 'http://www.kino-teatr.ru/acter/album/' + url;
				SetImageName('', url, '', IMAGE_PHOTO);
				inc(c);
			end;
			delete(temp, 1, i);
			i := Pos('<img src="/acter/album/', temp);
		end;
	end;
end;

//==================================================================================================
//  07. Сохранение картинки по ее URL в выбранный файл
//==================================================================================================
function SavePhoto(URL, FileName: string): Boolean;
	var
		Stream: TFileStream;
		Temp  : string;
begin          
	Temp:=DownloadURL(URL);
	if (Length(Temp)>0) and (Temp<>'-1') and (GetResponseCode=200)
	then   try
				Stream:=TFileStream.Create(FileName, fmCreate);
    			Stream.Write(Temp, Length(Temp));
    			Stream.Free;
					Result:=True;
	        except
				Result:=False
	        end
	else   Result:=False
end;

//==================================================================================================
//  Получение ссылки на страницу фильма по коду в формате сайта
//==================================================================================================
function GetMovieSiteURL(Code: string): string;
begin
	if Code<>''	then 
		result:='http://www.kino-teatr.ru/kino/movie/'+code+'/annot/'
	else   Result:=''
end;

//==================================================================================================
//  Получение ссылки на страницу актёра по коду в формате сайта
//==================================================================================================
function GetPersonSiteURL(Code: string): string;
begin
	if Code<>''
	then   Result:='http://kino-teatr.ru/kino/acter/'+Code+'/'
	else   Result:=''
end;

function ClearExtraBlankCharacters(text: string): string;
begin
	// Clear all extra blank charackters
	while (length(text) > 0) and (ord(text[1]) in [1..20, 32]) do
		delete(text, 1, 1);
	while (length(text) > 0) and (ord(text[length(text)]) in [1..20, 32]) do
		delete(text, length(text), 1);
	Result := text;
end;

begin
	monthes[1]:='января';
	monthes[2]:='февраля';
	monthes[3]:='марта';
	monthes[4]:='апреля';
	monthes[5]:='мая';
	monthes[6]:='июня';
	monthes[7]:='июля';
	monthes[8]:='августа';
	monthes[9]:='сентября';
	monthes[10]:='октября';
	monthes[11]:='ноября';
	monthes[12]:='декабря';
end.
