N9profile
[n9profile] / rulesmanager.cpp
1 #include "rulesmanager.h"
2 #include <QtGui/QStandardItemModel>
3 #include <QtCore/QDebug> //Debug pro informace
4 RulesManager::RulesManager(QObject *parent) :
5     QObject(parent)
6 {
7 }
8
9 /** Init
10   Creates an object ProfileDeamon and connects via ProfileDeamon: ConnectToDeamon
11   Create a model that will list all audio files
12   Then initializes the XML file using InitFile()
13   If the file exists so it attempts to read with readfile()
14    and if not it creates and initializes using CreateFile()
15 */
16 bool RulesManager::Init()
17 {//create a class to connect to deamon
18     InitWIFIIDModels();
19     ////qDebug() << "In file:" <<  __FILE__ << ":" << "on line:" << __LINE__ << " in function:" << __FUNCTION__ << "text::" << "bude init file ================= ";
20     //open the file
21     if(InitFile() == false) {
22         return false;
23     }
24
25     if(fileIDWifiNum.exists()) {
26         if(ReadfileIDWifiNum() == true){
27             LoadModelsWIFIIDTele();
28             return true;
29         } else {
30             qDebug() << "In file:" <<  __FILE__ << ":" << "on line:" << __LINE__ << " in function:" << __FUNCTION__ << "text::" << "neco spatne ve sceni souborů================= ";
31             return false;
32         }
33     } else {
34         if(CreatefileIDWifiNum() == true){
35             qDebug() << "In file:" <<  __FILE__ << ":" << "on line:" << __LINE__ << " in function:" << __FUNCTION__ << "text::" << "file created";
36             return true;
37         } else {
38             return false;
39         }
40     }
41     return false;
42 }
43
44 /** InitWIFIIDModels().
45 Used to initialize the models
46 and Horizontal Header Labels
47 */
48 bool RulesManager::InitWIFIIDModels()
49 {
50     model_of_CellID = new QStandardItemModel(this);
51     model_of_WiFi = new QStandardItemModel(this);
52     model_of_telephone_num = new QStandardItemModel(this);
53
54     QStringList labels;
55     labels << tr("Name") << tr("Id location") << tr("Profile") ;
56     model_of_CellID->setHorizontalHeaderLabels(labels);
57
58     labels.clear();
59     labels << tr("Name") << tr("Wifi name") << tr("Profile");
60     model_of_WiFi->setHorizontalHeaderLabels(labels);
61
62     labels.clear();
63     labels << tr("Name") << tr("Telephone") << tr("Profile");
64     model_of_telephone_num->setHorizontalHeaderLabels(labels);
65     return true;
66 }
67
68 //=============================================================
69 /** InitFile
70 Opens home folder and check if there is an dir NProfile and if not that it creates it
71 and set the file to Dir.filePath(profiles.xml)
72 */
73 bool RulesManager::InitFile()
74 {
75     QDir Dir = QDir::homePath();
76     //vytvori slozku pokud neni
77     if(!Dir.exists("NProfile")){
78         if(!Dir.mkdir("NProfile")){
79             qWarning() <<  __FILE__ << ":" << __LINE__ << " " << __FUNCTION__ << "Cannot create folder NProfile in home";
80             return false;
81         }
82     }
83     //switches to a folder
84     if(!Dir.cd("NProfile")){
85         qWarning() <<  __FILE__ << ":" << __LINE__ << " " << __FUNCTION__ << "cannot cd in NProfile";
86         return false;
87     }
88     fileIDWifiNum.setFileName(Dir.filePath("cellidwifinum.xml")); //set
89     return true;
90 }
91
92
93 //=============================================================================================================
94 /** CreatefileIDWifiNum
95 Open the file and create XML using CreateXmlTextIDWifi () and write to a file.
96 Sets the document and check with domDocumentIDWifiTelnum.setContent CheckDomDocIDWifi ()
97 and closes the file.
98
99     QFile fileIDWifiNum;
100     QDomDocument domDocumentIDWifiTelnum;
101 */
102 bool RulesManager::CreatefileIDWifiNum()
103 { //otevřu
104     ////qDebug() << "In file:" <<  __FILE__ << ":" << "on line:" << __LINE__ << " in function:" << __FUNCTION__ << "text::" << "vytvorim wifi soubor ================= ";
105     if (!fileIDWifiNum.open(QIODevice::ReadWrite | QIODevice::Text)){
106         //////qDebug() << "In file:" <<  __FILE__ << ":" << "on line:" << __LINE__ << " in function:" << __FUNCTION__ << "text::" << "Cannot open file";
107         return false;
108     }
109     QString errorStr;
110     int errorLine;
111     int errorColumn;
112     QTextStream out(&fileIDWifiNum);
113     QString text = CreateXmlTextIDWifi(); //create text xml
114     out.setCodec("UTF-8");//set utf 8
115     out.setAutoDetectUnicode(true);
116     out << text;//write
117     out.flush(); //
118
119     if (!domDocumentIDWifiTelnum.setContent(text, false, &errorStr, &errorLine,
120                                             &errorColumn)) {
121         //////qDebug() << "In file:" <<  __FILE__ << ":" << "on line:" << __LINE__ << " in function:" << __FUNCTION__ << "text::" << "Cannot set content " << errorStr << "line " << errorLine << "Column " << errorColumn;
122         fileIDWifiNum.close();
123         return false;
124     }
125     //check
126     if(!CheckDomDocIDWifi()) {
127         //////qDebug() << "In file:" <<  __FILE__ << ":" << "on line:" << __LINE__ << " in function:" << __FUNCTION__ << "text::" <<  "Error in document, this is not calendar file  ";
128         fileIDWifiNum.close();
129         return false;
130     }
131     fileIDWifiNum.close();//close
132     initIDWIFTeleDoc(); //add elements
133
134     return true;
135 }
136
137
138 /** CreateXmlTextIDWifi
139 Creates the xml text
140 */
141 QString RulesManager::CreateXmlTextIDWifi()
142 {
143     QString text("");
144     text += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
145     text += "<!DOCTYPE NProfIDWifi>\n";
146     text +="<NProfIDWifi version=\"1.0\">\n";//začátek
147     text += "</NProfIDWifi>\n";//konec souboru
148     return text;
149 }
150
151 /** initIDWIFTeleDoc
152 Add chield element to doc
153 */
154 void RulesManager::initIDWIFTeleDoc()
155 {
156     QDomElement root = domDocumentIDWifiTelnum.documentElement();
157     QDomElement Wifi = domDocumentIDWifiTelnum.createElement("WIFI");
158     root.appendChild(Wifi);
159     QDomElement LocID = domDocumentIDWifiTelnum.createElement("LOCID");
160     root.appendChild(LocID);
161     QDomElement Tele = domDocumentIDWifiTelnum.createElement("TELENUM");
162     root.appendChild(Tele);
163 }
164 //=============================================================================================================
165 //=============================================================================================================
166 /** ReadfileIDWifiNum
167 Opens a file and reads the XML document using domDocumentIDWifiTelnum.setContent and check it with CheckDomDocIDWifi ()
168 */
169 bool RulesManager::ReadfileIDWifiNum()
170 {
171     ////qDebug() << "In file:" <<  __FILE__ << ":" << "on line:" << __LINE__ << " in function:" << __FUNCTION__ << "text::" << "nacitam wifi soubor ================= ";
172     if (!fileIDWifiNum.open(QIODevice::ReadWrite | QIODevice::Text)){
173         ////qDebug() <<  __FILE__  << __LINE__  << __FUNCTION__ << "Cannot open file";
174         return false;
175     }
176     QString errorStr;
177     int errorLine;
178     int errorColumn;
179     if (!domDocumentIDWifiTelnum.setContent((QIODevice * )&fileIDWifiNum, false, &errorStr, &errorLine,
180                                             &errorColumn)) {
181         ////qDebug() << "In file:" <<  __FILE__ << ":" << "on line:" << __LINE__ << " in function:" << __FUNCTION__ << "text::" << "Cannot set content " << errorStr << "line " << errorLine << "Column " << errorColumn;
182         fileIDWifiNum.close();
183         return false;
184     }
185     ////qDebug() << "In file:" <<  __FILE__ << ":" << "on line:" << __LINE__ << " in function:" << __FUNCTION__ << "text::" << "tisk toho dokumentu" << domDocumentIDWifiTelnum.toString();
186     //control
187     if(!CheckDomDocIDWifi()) {
188         ////qDebug() << "In file:" <<  __FILE__ << ":" << "on line:" << __LINE__ << " in function:" << __FUNCTION__ << "text::" << "Error in document, this is not calendar file ";
189         fileIDWifiNum.close();
190         return false;
191     }
192     //  print();
193     fileIDWifiNum.close();
194     return true;
195 }
196
197
198 /** CheckDomDocIDWifi
199 Checks if the document is in order
200 */
201 bool RulesManager::CheckDomDocIDWifi()
202 {
203     QDomElement root = domDocumentIDWifiTelnum.documentElement();
204     if (root.tagName() != "NProfIDWifi") {
205         //////qDebug() << "In file:" <<  __FILE__ << ":" << "on line:" << __LINE__ << " in function:" << __FUNCTION__ << "text::" << "Error in root";
206         return false;
207     } else if (root.hasAttribute("version")
208         && root.attribute("version") != "1.0") {
209         //////qDebug() << "In file:" <<  __FILE__ << ":" << "on line:" << __LINE__ << " in function:" << __FUNCTION__ << "text::" << "Error in version";
210         return false;
211     }
212     return true;
213 }
214
215
216 //===============================================================================================
217
218 /** LoadModelsWIFIIDTele().
219 Load rules for network and numbers from xml document into tables
220 */
221 void  RulesManager::LoadModelsWIFIIDTele()
222 {
223     ////qDebug() << "In file:" <<  __FILE__ << ":" << "on line:" << __LINE__ << " in function:" << __FUNCTION__ << "text::" << "bude nacitat";
224     QList<QStandardItem *>  items;
225     //labels << tr("Name") << tr("Wifi name") << tr("Profile");
226     QDomElement root = domDocumentIDWifiTelnum.documentElement();
227     QDomElement eleLocId = root.firstChildElement("LOCID");
228     QDomElement eleWifi = root.firstChildElement("WIFI");
229     QDomElement eleTelenum = root.firstChildElement("TELENUM");
230
231     QDomElement first = eleLocId.firstChildElement(); //ziskám první prvek
232     QDomElement second;
233     while(!first.isNull()) //pro vsechny pravidla
234     {
235          second = first.firstChildElement();
236         while(!second.isNull()) //pravidla maj 3 elementy
237         {
238             items.append(new QStandardItem(second.text())); //text je hodnota
239             second = second.nextSiblingElement();
240         }
241         model_of_CellID->appendRow(items);
242         items.clear();
243         ////qDebug() << "Element name and text: " << first.tagName() << first.text() << "a atribut je ???????" << first.attribute(QString("id"));
244         first = first.nextSiblingElement();
245     }
246
247     first = eleWifi.firstChildElement(); //ziskám první prvek
248
249     ////qDebug() << "In file:" <<  __FILE__ << ":" << "on line:" << __LINE__ << " in function:" << __FUNCTION__ << "text::" << "nastavuje modely";
250     while(!first.isNull())
251     {
252          second = first.firstChildElement();
253         ////qDebug() << "Element name and text: " << first.tagName() << first.text() << "a atribut je ???????" << first.attribute(QString("id"));
254         while(!second.isNull()) //pravidla maj 3 elementy
255         {
256             items.append(new QStandardItem(second.text())); //text je hodnota
257             second = second.nextSiblingElement();
258         }
259         model_of_WiFi->appendRow(items);
260         items.clear();
261         first = first.nextSiblingElement();
262     }
263
264     first = eleTelenum.firstChildElement(); //ziskám první prvek
265
266     ////qDebug() << "In file:" <<  __FILE__ << ":" << "on line:" << __LINE__ << " in function:" << __FUNCTION__ << "text::" << "nastavuje modely";
267     while(!first.isNull())
268     {
269             second = first.firstChildElement();
270         ////qDebug() << "Element name and text: " << first.tagName() << first.text() << "a atribut je ???????" << first.attribute(QString("id"));
271         while(!second.isNull()) //pravidla maj 3 elementy
272         {
273            qDebug() << "In file:" <<  __FILE__ << ":" << "on line:" << __LINE__ << " in function:" << __FUNCTION__ << "text::" << "nastavuje modely a seckond je " << second.text();
274             items.append(new QStandardItem(second.text())); //text je hodnota
275             second = second.nextSiblingElement();
276         }
277         model_of_telephone_num->appendRow(items);
278         items.clear();
279         first = first.nextSiblingElement();
280     }
281 }
282 //===========================================
283 /** SaveProfilesToXml
284 Saves the document to a file
285 */
286 void RulesManager::SaveProfilesToXml()
287 {
288     //update before saving
289     UpdateWifiXml();
290     UpdateIDLocXml();
291     UpdateTelNumXml();
292
293     if (!fileIDWifiNum.open(QIODevice::WriteOnly | QIODevice::Text)){
294         //////qDebug() <<  __FILE__  << __LINE__  << __FUNCTION__ << "Cannot open file";
295     }
296
297     QTextStream outt(&fileIDWifiNum);
298     outt.setCodec("UTF-8");//set utf 8
299     outt.setAutoDetectUnicode(true);
300     outt << domDocumentIDWifiTelnum.toString();//write
301     outt.flush(); //
302     fileIDWifiNum.close();
303 }
304
305 /** UpdateIDLocXml
306     Update id loc part of xml document
307 */
308 void RulesManager::UpdateIDLocXml()
309 {
310     QDomElement root = domDocumentIDWifiTelnum.documentElement();//zikam root elemnet
311     QDomElement profil_old = root.firstChildElement("LOCID");//najdu starej pro id mista
312     QDomElement profil_new = this->CreateNewIDEle("LOCID", model_of_CellID);//vytvorim novy z modelu
313     root.replaceChild(profil_new, profil_old); //vymenim
314     // emit  s_profile_update(Data->GetName());
315 }
316
317 /** UpdateWifiXml
318   Update wifi part of xml document
319 */
320 void RulesManager::UpdateWifiXml()
321 {
322     QDomElement root = domDocumentIDWifiTelnum.documentElement();//zikam root elemnet
323     QDomElement profil_old = root.firstChildElement("WIFI");//najdu starej pro id mista
324     QDomElement profil_new = this->CreateNewIDEle("WIFI", model_of_WiFi);//vytvorim novy z modelu
325     root.replaceChild(profil_new, profil_old); //vymenim
326     // emit  s_profile_update(Data->GetName());
327 }
328
329 /** UpdateTelNumXml
330   Update tel part of xml document
331 */
332 void RulesManager::UpdateTelNumXml()
333 {
334     QDomElement root = domDocumentIDWifiTelnum.documentElement();//zikam root elemnet
335     QDomElement profil_old = root.firstChildElement("TELENUM");//najdu starej pro id mista
336     QDomElement profil_new = this->CreateNewIDEle("TELENUM", model_of_telephone_num);//vytvorim novy z modelu
337     root.replaceChild(profil_new, profil_old); //vymenim
338     // emit  s_profile_update(Data->GetName());
339 }
340
341 /** CreateNewIDEle
342 Save all records from table to xml and return element
343  \param model Pointer to model
344  \param name Name
345
346 */
347 QDomElement RulesManager::CreateNewIDEle(QString name, QStandardItemModel * model)
348 {
349     QDomElement rules = domDocumentIDWifiTelnum.createElement(name); //create element
350     QDomElement rule;
351     QString str;
352     for(int i = 0; i < model->rowCount(); i++)
353     {
354         rule = domDocumentIDWifiTelnum.createElement(QString("rule") + str.setNum(i));
355         CreateNodeID(&rule, QString("name"), model->item(i,0)->data(Qt::DisplayRole).toString());
356         CreateNodeID(&rule, QString("id"), model->item(i,1)->data(Qt::DisplayRole).toString());
357         CreateNodeID(&rule, QString("profile"), model->item(i,2)->data(Qt::DisplayRole).toString());
358         rules.appendChild(rule);
359     }
360     //labels << tr("Name") << tr("Wifi name") << tr("Profile");
361     return rules;
362 }
363
364 /** createNode
365 Creates an item in the XML file and adds it to the record
366  \param id Pointer to the element in xml
367  \param name Name
368  \param text wifi name or id location
369   \param attribute atribute for name of profile
370 */
371 void RulesManager::CreateNodeID(QDomElement * rule, QString name, QString text)
372 {
373     QDomElement ruleE = domDocumentIDWifiTelnum.createElement(name);
374     QDomText newTitleText = domDocumentIDWifiTelnum.createTextNode(text);
375     ruleE.appendChild(newTitleText);
376     rule->appendChild(ruleE);
377 }
378
379 //==================================================================================================
380 /** deleteProfilesNamesFromModels
381 Delete profile name in models
382      \param profile_name Profile name
383 */
384 void RulesManager::deleteProfilesNamesFromModels(QString profile_name)
385 {
386     QList<QStandardItem *> listitems;
387     listitems = model_of_CellID->findItems(profile_name, Qt::MatchExactly, 2);
388     ////qDebug() << "In file:" <<  __FILE__ << ":" << "on line:" << __LINE__ << " in function:" << __FUNCTION__ << "text::" << "budou se mazat jmena profilu";
389
390     foreach(QStandardItem * item, listitems )
391     {
392         ////qDebug() << "In file:" <<  __FILE__ << ":" << "on line:" << __LINE__ << " in function:" << __FUNCTION__ << "text::" << "nasel v tabulce pro cell toto" << item->data(Qt::DisplayRole).toString();
393         item->setData(QVariant(""),Qt::DisplayRole);
394     }
395     listitems.clear();
396
397     listitems = model_of_WiFi->findItems(profile_name, Qt::MatchExactly, 2);
398     foreach(QStandardItem * item, listitems )
399     {
400         ////qDebug() << "In file:" <<  __FILE__ << ":" << "on line:" << __LINE__ << " in function:" << __FUNCTION__ << "text::" << "nasel v tabulce pro cell toto" << item->data(Qt::DisplayRole).toString();
401         item->setData(QVariant(""),Qt::DisplayRole);
402     }
403     listitems.clear();
404
405     listitems = model_of_telephone_num->findItems(profile_name, Qt::MatchExactly, 2);
406     foreach(QStandardItem * item, listitems )
407     {
408         ////qDebug() << "In file:" <<  __FILE__ << ":" << "on line:" << __LINE__ << " in function:" << __FUNCTION__ << "text::" << "nasel v tabulce pro cell toto" << item->data(Qt::DisplayRole).toString();
409         item->setData(QVariant(""),Qt::DisplayRole);
410     }
411 }
412
413 /** GetCellIDModel
414     Return pointer to model
415 */
416 QStandardItemModel * RulesManager::GetCellIDModel()
417 {
418     return model_of_CellID;
419 }
420
421 /** GetWiFiModel
422         Return pointer to model
423 */
424 QStandardItemModel * RulesManager::GetWiFiModel()
425 {
426     return model_of_WiFi;
427 }
428
429 /** GetWiFiModel
430         Return pointer to model
431 */
432 QStandardItemModel * RulesManager::GetTelNumModel()
433 {
434     return model_of_telephone_num;
435 }
436