//
//  PickerView.m
//  X-BASIC'
//
//  Created by AIG-Soft on 2012/8/13
//  Copyright 2012-2015 AIG-Soft. All rights reserved.
//

#import "PickerView.h"
#import "Setup.h"
#import	"click.h"
#import "libs.h"
#import "main.h"

@interface PickerView()
{
	
}
@property (nonatomic,strong) UIButton *nextButton0;
@end

@implementation PickerView

//-------------------------------------------------------------------

-(void)viewDidLoad
{
	printSelf();
	[super viewDidLoad];
	
	frame0.size=self.view.frame.size; // 自分のサイズを保存
	
	// デリゲートとソース設定;nib部なのでここに置く
	_pickerView.delegate  =self;
	_pickerView.dataSource=self;
	
	CALayer *layer=_pickerView.layer;
	layer.cornerRadius  = 3;
	layer.masksToBounds = NO;
	layer.shadowOffset  = CGSizeMake(2, 2);
	layer.shadowRadius  = 2;
	layer.shadowOpacity = 1;
	
	lblInfo.layer.cornerRadius=
	lblInfoL.layer.cornerRadius=2;

	nslog(@"nextButton=%@",_nextButton);
	
	// デフォルトは次ボタン/削除ボタン非表示
	fLblInfoHidden	  =
    lblInfo.hidden    = lblInfoL.hidden   =YES;
	fnextButtonHidden =
    _nextButton.hidden= _nextButtonL.hidden=YES;
	fdelButtonHidden  =
    _delButton.hidden = _delButtonL.hidden =YES;

	// これでもだめ
//	// 何故かpickerView内のnextButtonが接続されないのでここでプログラム的に作る
//	self.nextButton0=[[UIButton alloc]initWithFrame:self.nextButton.frame]; // retainするため
//	nslog(@"self.nextButton0=%@",self.nextButton0);
//	self.nextButton=self.nextButton0; // self.nextButtonはweakなので
//	[self.view addSubview:self.nextButton];
	
	if (getSystemVersion()<8.0) {
		// iOS7だけ
		if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
			// iPadのPopover内に表示するときは元々のxib内で設定されているStatusBar+Navi分を除いておく
			for (UIView *subView in self.view.subviews) {
				CGRect frame=subView.frame;
				frame.origin.y-=(20+44);
				subView.frame=frame;
			}
		}
	}
}

- (void)viewWillAppear:(BOOL)animated
{
	printSelf();
	[super viewWillAppear:animated];
	//
	// 初期画面方向設定
	UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation]; // 起動時の画面方向
	[self willAnimateRotationToInterfaceOrientation:orientation duration:0];

	// カーソル位置設定;ここでしないとうまくいかない
	[_pickerView selectRow:self.selectRow inComponent:0 animated:NO];
	_pickerView.showsSelectionIndicator=YES;
	//
	self.preferredContentSize=frame0.size; // サイズを戻す(これが重要)

#if 0
	if (getSystemVersion()<8.0) {
		// iOS7だけ
		if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
			// iPadのPopover内に表示するときは元々のxib内で設定されているStatusBar+Navi分を除いておく
			for (UIView *subView in self.view.subviews) {
				CGRect frame=subView.frame;
				frame.origin.y-=(20+44);
				subView.frame=frame;
			}
		}
	}
#endif

}

//----------------------

- (void)initPickerView:(id)retTarget retSelector:(SEL)retSelector title:(NSString *)title cols:(NSArray *)cols selectRow:(NSUInteger)selectRow_
{
	nslog(@"initPickerView(2):title=%@",title);
	[self initPickerView:retTarget retSelector:retSelector title:title cols:cols selectRow:selectRow_ btnTitle:NSLocalStr(@"SAVE")];
}

- (void)initPickerView:(id)retTarget retSelector:(SEL)retSelector title:(NSString *)title cols:(NSArray *)cols selectRow:(NSUInteger)selectRow_
			  btnTitle:(NSString *)btnTitle
{
	nslog(@"initPickerView(3):title=%@",title);
	[self initPickerView:retTarget retSelector:retSelector title:title cols:cols selectRow:selectRow_ btnTitle:btnTitle cancelSelector:nil];
}

- (void)initPickerView:(id)retTarget retSelector:(SEL)retSelector title:(NSString *)title cols:(NSArray *)cols selectRow:(NSUInteger)selectRow_
			  btnTitle:(NSString *)btnTitle
		   cancelSelector:(SEL)cancelSelector
{
	nslog(@"initPickerView(1):title=%@/btn=%@",title,btnTitle);
	// タイトル設定
	self.title=title;
	
	frame0=self.view.frame; // popoverのサイズを設定するために保存:iPhone用のそれを使う

	// 項目設定
	rows=[cols count];
	nslog(@"rows=%d",(int)rows);
	self.rowStrings=cols; // propertyを使うので
	// カーソル位置計算
	self.selectRow=selectRow_;
	// ボタン設定
	UIBarButtonItem *tempBarItem=	[[UIBarButtonItem alloc]initWithTitle:btnTitle
																		  style:UIBarButtonItemStyleDone
																		 target:retTarget
																		 action:retSelector];
	self.navigationItem.leftBarButtonItem=tempBarItem;
	//
	if (cancelSelector!=nil) {
		tempBarItem=	[[UIBarButtonItem alloc]initWithTitle:NSLocalStr(@"CANCEL")
																	  style:UIBarButtonItemStyleDone
																	 target:retTarget
																	 action:cancelSelector];
		self.navigationItem.rightBarButtonItem=tempBarItem;
		self.navigationItem.rightBarButtonItem.tintColor=[UIColor redColor];
	}
}

- (void)reSetPickerView:(NSArray *)cols selectRow:(NSUInteger)selectRow_
{
	printSelf();
	// 項目設定
	rows=[cols count];
	nslog(@"rows=%d",(int)rows);
	self.rowStrings=cols; // propertyを使うので
	// カーソル位置計算
	self.selectRow=selectRow_;
	// 項目再表示
	[_pickerView reloadAllComponents];
}

//-------------------------------------------------------------------

-(void)setNextButtonAction:(id)target_ nextSelector:(SEL)selector_
{
	printSelf();
	nextTarget	=target_;
	nextSelector=selector_;
}

-(IBAction)nextButtonAction:(id)sender
{
	printSelf();
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"        // 警告回避のため
	[nextTarget performSelector:nextSelector];
#pragma clang diagnostic pop
}

-(void)nextButtonHidden:(BOOL)fhidden
{
	printSelf();
	fnextButtonHidden=fhidden;
	if (fPortrait) {
        _nextButton.hidden  = fhidden;
        _nextButtonL.hidden = YES;
	} else {
        _nextButton.hidden  = YES;
        _nextButtonL.hidden = fhidden;
	}
}

-(void)setNextButtonTitle:(NSString *)text
{
	printSelfs(@"%@",text);
	testLabel.text=text;
	[_nextButton  setTitle:text forState:UIControlStateNormal];
	[_nextButtonL setTitle:text forState:UIControlStateNormal];
	nslog(@"_nextButton=%@",self.nextButton);
}

//-------------------------------------------------------------------

-(void)setDelButtonAction:(id)target_ delSelector:(SEL)selector_
{
	printSelf();
	delTarget	=target_;
	delSelector=selector_;
}

-(IBAction)delButtonAction:(id)sender
{
	printSelf();
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"        // 警告回避のため
	[delTarget performSelector:delSelector];
#pragma clang diagnostic pop
}

-(void)delButtonHidden:(BOOL)fhidden
{
	printSelf();
	fdelButtonHidden=fhidden;
	if (fPortrait) {
        _delButton.hidden  = fhidden;
        _delButtonL.hidden = YES;
	} else {
        _delButton.hidden  = YES;
        _delButtonL.hidden = fhidden;
	}
}

-(void)setDelButtonTitle:(NSString *)text
{
	printSelfs(@"%@",text);
	[_delButton  setTitle:NSLocalStr(text) forState:UIControlStateNormal];
	[_delButtonL setTitle:NSLocalStr(text) forState:UIControlStateNormal];
}

//-------------------------------------------------------------------

-(void)lblInfoHidden:(BOOL)fhidden
{
	fLblInfoHidden=fhidden;
	if (fPortrait) {
        lblInfo.hidden  = fhidden;
        lblInfoL.hidden = YES;
	} else {
        lblInfo.hidden  = YES;
        lblInfoL.hidden = fhidden;
	}
}

-(void)setLblInfoText:(NSString *)text
{
	nslog(@"setLblInfo=%@",text);
	lblInfoL.text=text;
	lblInfo.text =text;
}

//-------------------------------------------------------------------

// 列数を返す
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
	// すべての項目が列＝1
	return(1);
}

// 指定行の項目数を返す
// 仕様書参照のこと
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
	return(rows);
}

// 指定行項目の文字列を返す
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
	// iOS6以前用/iOS7標準の表示
	return self.rowStrings[row];
}

#if 0
-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
	// iOS7でiOS6のような表示にする
	// http://blog.hawkimedia.com/2013/08/ios7-uipickerview-customization/より
	// このデリゲートはiOS6から利用でき、-(NSString *)pickerViewより優先される
	// FontSelect.mで使っているので参照のこと
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, pickerView.frame.size.width, 44)];
    label.backgroundColor = [UIColor lightGrayColor];
    label.textColor = [UIColor blackColor];
    label.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:18];
    label.text = [NSString stringWithFormat:@"  %d", row+1];
    return label;
}
#endif

// 選択時に呼び出される
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
	nslog(@"選択:(%d,%d)",(int)row,(int)component); // componentは0のはず
	self.selectRow=row;
#if 0
	// ここにこれを入れると、選択直後に表示が変わる
	[pickerView reloadAllComponents]; // 項目の全読み込み直し
#endif
}

//----------------------------------------------
// 画面回転
//----------------------------------------------

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration
// 回転検出：回転前
{
	printSelfs(@"Orientation=%d",(int)interfaceOrientation);
	understandOrientation(interfaceOrientation); // 画面方向を記録
	// interfaceOrientationは新しい方向
	CGRect frame=_pickerView.frame;
	switch (interfaceOrientation) {
		default:
		case UIInterfaceOrientationPortrait:
		case UIInterfaceOrientationPortraitUpsideDown:
			nslog(@"縦方向");
			fPortrait=YES;
			// 横用を無効にする
			lblInfoL.hidden=
			_delButtonL.hidden=
			_nextButtonL.hidden=YES;
			// 縦用を有効にする
			lblInfo.hidden	 =fLblInfoHidden;
			_delButton.hidden =fdelButtonHidden;
			_nextButton.hidden=fnextButtonHidden;
			frame.size.width=300;
			_pickerView.frame=frame;
			break;
		case UIInterfaceOrientationLandscapeLeft:
		case UIInterfaceOrientationLandscapeRight:
			nslog(@"横方向");
			fPortrait=NO;
			// 縦用を無効にする
			lblInfo.hidden=
			_delButton.hidden=
			_nextButton.hidden=YES;
			// 横用を有効にする
			lblInfoL.hidden   =fLblInfoHidden;
			_delButtonL.hidden =fdelButtonHidden;
			_nextButtonL.hidden=fnextButtonHidden;
			//
			frame.size.width=287;
			_pickerView.frame=frame;
			break;
	}
}

// 画面を回転して良いかどうか
-(BOOL)shouldAutorotate
{
	printSelf();
	if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
		// iPadのpopover内では回転させない
		return NO;
	}
	return shouldAutorotateByMain();
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
	return (supportedInterfaceOrientationsByMain());
}

//-------------------------------------------------------------------

#pragma mark -
#pragma mark Memory management

#ifdef DEBUG
- (void)didReceiveMemoryWarning
{
	printSelf();
	[super didReceiveMemoryWarning];
}

#endif

@end
