//
//  AlertViewSub.m
//  X-BASIC'
//
//  Created by AIG-Soft on 2012/08/16.
//  Copyright (c) 2012 AIG-Soft. All rights reserved.
//

#import "AlertViewSub.h"
#import "click.h"

@implementation AlertViewSub

-(void)releaseAlert:(id)sender
{
	printSelf();
	if (alertView!=nil) {
		alertView=nil; // 使ってない印
	}
}

-(void)alertView:(UIAlertView *)alertView_ willDismissWithButtonIndex:(NSInteger)buttonIndex
// AlertViewのボタンが押された
// デリゲート処理
{
	printSelf();
	if (buttonIndex!=alertView_.cancelButtonIndex) {
		nslog(@"OK");
		[target performSelector:selector withObject:nil afterDelay:delay];
	}
	else {
		nslog(@"キャンセル");
		if (targetCancel!=nil) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"        // 警告回避のため
			[targetCancel performSelector:selectorCancel withObject:nil];
#pragma clang diagnostic pop
		}
	}
	// これを抜けるとアラートが消える
	// 終わったちょっと後にalertViewを解放する
	[self performSelector:@selector(releaseAlert:) withObject:nil afterDelay:0.1];
}


-(void)alertExecuteMain:(BOOL)fCheck target:(id)target_ selector:(SEL)selector_ delay:(NSTimeInterval)delay_ title:(NSString *)title message:(NSString *)message
{
	printSelf();
	clickSound();
	target	=target_;
	selector=selector_;
	delay	=delay_;
	[self releaseAlert:nil]; // 前の残骸があったら消しておく
	if (fCheck) {
		// 確認後実行
		// alertViewは毎回alloc+initしないと正常に表示されない
		alertView=[[UIAlertView alloc]
					   initWithTitle:title
							 message:NSLocalStr(message)
							delegate:self
				   cancelButtonTitle:NSLocalStr(@"NO" )	// ボタン番号=cancelButtonIndex
				   otherButtonTitles:NSLocalStr(@"YES")	// ボタン番号=firstOtherButtonIndex 
				   ,nil
				   ];
//		[alertView dismissWithClickedButtonIndex:alertView.firstOtherButtonIndex animated:YES]; // アラートを消すボタンの設定
		// 表示
		[alertView show]; // ここから送信
	} else {
		nslog(@"即時実行");
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"        // 警告回避のため
		[target performSelector:selector withObject:nil];
#pragma clang diagnostic pop
	}
}

-(void)alertExecute:(BOOL)fCheck target:(id)target_ selector:(SEL)selector_ delay:(NSTimeInterval)delay_ title:(NSString *)title message:(NSString *)message
{
	printSelf();
	targetCancel  =nil;
	selectorCancel=0;
	[self alertExecuteMain:fCheck target:target_ selector:selector_ delay:delay_ title:title message:message];
}

-(void)alertExecuteWithCancel:(BOOL)fCheck target:(id)target_ selector:(SEL)selector_ delay:(NSTimeInterval)delay_ title:(NSString *)title message:(NSString *)message
				 targetCancel:(id)targetCancel_ selectorCancel:(SEL)selectorCancel_
{
	targetCancel  =targetCancel_;
	selectorCancel=selectorCancel_;
	[self alertExecuteMain:fCheck target:target_ selector:selector_ delay:delay_ title:title message:message];
}


-(void)dealloc
{
	printSelf();
	[self releaseAlert:nil];
}

@end
